Maximum Depth of Binary Tree
The depth of a tree is 1 (for the root) plus the deeper of its two subtrees. An empty tree has depth 0. Recursion computes it bottom-up: each node waits for its children's depths.
▶ Watch the animated traceTraced input: root = [3, 9, 20, null, null, 15, 7] → 3. Original problem: neetcode.io/problems/depth-of-binary-tree
Complexity
BestO(n)
AverageO(n)
WorstO(n)
SpaceO(h)
Every node is visited once; the call stack is as deep as the tree (h), O(n) for a skewed tree.
Key idea
- Base case:
nullhas depth 0. - Recursive case:
1 + max(depth(left), depth(right)). - BFS counting levels gives the same answer iteratively.
Common mistakes
- Returning 1 for a null node (off by one).
- Very deep skewed trees can overflow the call stack; BFS avoids recursion.
Solution
Java
int maxDepth(TreeNode root) {
if (root == null) return 0;
int left = maxDepth(root.left);
int right = maxDepth(root.right);
int depth = 1 + Math.max(left, right);
return depth;
}Python
def maxDepth(root: Optional[TreeNode]) -> int:
if not root: return 0
left = maxDepth(root.left)
right = maxDepth(root.right)
return 1 + max(left, right)C++
int maxDepth(TreeNode* root) {
if (!root) return 0;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return 1 + max(left, right);
}Edge cases
Each one has its own trace in the interactive view.
| Case | Input | Answer |
|---|---|---|
| Empty tree The base case returns immediately. | root = [] | 0 |
| Single node Both children return 0. | root = [1] | 1 |
| Skewed tree A chain: the recursion is as deep as the number of nodes. | root = [1, 2, null, 3, null, 4] | 4 |
| Unbalanced Only the right subtree adds depth. | root = [1, null, 2] | 2 |