Learning Outcome
After this lesson, you should be able to define tree height recursively and return the maximum depth from the root.
Problem Statement
Given the root of a binary tree, return its maximum depth. The maximum depth is the number of nodes on the longest path from the root to a leaf.
| Input | Output | Why |
|---|---|---|
[3,9,20,null,null,15,7] | 3 | The longest root-to-leaf path has 3 nodes. |
Brute Force Approach
Store every root-to-leaf path, then return the length of the longest path.
This works but stores unnecessary path lists. The depth can be computed directly.
Optimized Approach
For any node, the maximum depth is 1 + max(depth(left), depth(right)). A null node contributes depth 0.
Exact Pseudocode
maxDepth(node):
if node is null:
return 0
leftDepth = maxDepth(node.left)
rightDepth = maxDepth(node.right)
return 1 + max(leftDepth, rightDepth)
Reference Code
class Solution:
def maxDepth(self, root):
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))Sample Dry Run
| Node | leftDepth | rightDepth | Return |
|---|---|---|---|
| 9 | 0 | 0 | 1 |
| 15 | 0 | 0 | 1 |
| 7 | 0 | 0 | 1 |
| 20 | 1 | 1 | 2 |
| 3 | 1 | 2 | 3 |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(n) | Each node contributes once. |
| Space | O(h) | The recursion stack depends on height. |
Edge Cases
- Empty tree returns
0. - Single-node tree returns
1. - Skewed tree has height
n.
Interview Checklist
- Use
0for null depth. - Add
1for the current node. - Take the maximum of left and right depth.
FAQs
Why is null depth zero?
A null child contributes no nodes to a root-to-leaf path.
Is depth counted in nodes or edges?
This common version counts nodes. Always confirm wording if the interviewer says edges.
What is the core pattern?
Recursive height calculation.