Height of Binary Tree
Compute maximum depth using recursive DFS and bottom-up subtree heights.
Key concepts at a glance — for those who already know the basics.
Problem Statement
Height (Maximum Depth) of Binary Tree
Input: [3,9,20,null,null,15,7]
Output: 3
Input: [1,null,2]
Output: 2
Constraints
- Nodes range: [0, 10^4]
- Node values range: [-100, 100]
The Formula
height(node) = 1 + max(left, right)
Null node contributes 0 depth in node-count formulation.
How to Think
Go to leaves first
Leaves are smallest subproblems and return 1.
Return subtree height
Each call returns one integer to parent.
Take max of both sides
Longest branch determines depth at each node.
Code
Complexity
Time
O(n)
Visit each node exactly once.
Space
O(h)
Recursion stack equals tree height.
Interview Uses
Balanced Binary Tree
Compare left and right subtree heights at each node.
Diameter of Binary Tree
Use heights to compute longest path through each node.
Max Path / Tree DP
Height is a core subroutine in many tree DP problems.
Platform difference checks
Some sites ask node depth, others ask edge height.
Ready to watch recursion live?
Open the visualizer and follow how each node returns its subtree height.