Multiple coding and database queries
Filed under Accolite
Free read 1 of 3If the current node is null, return a height of 0.
The question
Given a binary tree, determine its maximum height (the number of nodes along the longest path from the root node down to the farthest leaf node).
Constraints
- The number of nodes in the tree is in the range [0, 10^4].
- -100 <= Node.val <= 100
Examples
- Input
- root = [3,9,20,null,null,15,7]
- Output
- 3
- Why
- The longest path is 3 -> 20 -> 15 or 3 -> 20 -> 7, which has 3 nodes.
Approach
If the current node is null, return a height of 0.
Recursively calculate the height of the left subtree and the right subtree.
The height of the current node is 1 plus the maximum of the left and right heights.
Tips
- What they are testing: Ensure the code handles an empty tree (height 0) and a tree with only one node (height 1).
- Common mistake: Confusing 'height' (nodes on path) with 'edges' (height - 1); clarify with the interviewer.
Related Accolite questions
Collected from public candidate posts and coding forums. Updated Nov 2026.