Given the root of a binary tree, return its maximum depth — the number of nodes along the longest path from the root down to the farthest leaf.
The tree is given in level-order (breadth-first), using null for missing children.
Input: root = [3, 9, 20, null, null, 15, 7] Output: 3 The longest root-to-leaf path 3 -> 20 -> 15 (or 3 -> 20 -> 7) has 3 nodes.
Input: root = [1, null, 2] Output: 2 The path 1 -> 2 has 2 nodes.
- The number of nodes is in the range [0, 10^4] - -100 <= Node.val <= 100
The maximum depth of a tree is one more than the deeper of its two subtrees' depths. That single sentence is the whole recursion: an empty tree has depth 0, and any node contributes 1 on top of max(left depth, right depth).
“Depth in nodes or edges?”
Here it's the number of nodes on the longest root-to-leaf path; an empty tree is 0, a single node is 1.
“Can the tree be empty?”
Yes — return 0.
The depth of a tree is one plus the maximum depth of its two subtrees, with an empty tree being zero.
That's a direct recursion; I could also count levels with a breadth-first traversal.
Worked example — tree [3, 9, 20, null, null, 15, 7]
3 depth(15)=1, depth(7)=1
/ \ depth(20)=1+max(1,1)=2
9 20 depth(9)=1
/ \ depth(3)=1+max(1,2)=3
15 7
answer: 3
The recurrence is the entire solution; the base case (null → 0) makes it terminate.
You need both children's depths before you can answer for the parent — classic bottom-up recursion.
The number of levels in a breadth-first traversal equals the maximum depth — a natural iterative alternative.
| BFS level count | Recursive depth | |
|---|---|---|
| Idea | Count levels with a queue | 1 + max(depth(left), depth(right)) |
| Time | O(n) | O(n) |
| Space | O(n) queue | O(height) recursion |
Both are O(n); the recursion is a one-liner, BFS avoids deep call stacks. Full code is in the Approaches selector below.
Key takeaway
Maximum depth = 1 + max(left depth, right depth), with an empty tree contributing 0. O(n) time, O(height) space recursively.
depth(node):
if node is null: return 0
return 1 + max(depth(node.left), depth(node.right))