Call stack one frame per maxDepth call · newest on the right · badges = returned depth
public int maxDepth(TreeNode root) { if (root == null) { return 0; } int left = maxDepth(root.left); int right = maxDepth(root.right); return 1 + Math.max(left, right);}
- root
- —
- left
- —
- right
- —
- return
- —
- frames
- 0
Why it works
- The definition is the code. An empty tree has depth 0; any other tree is its root plus the deeper of its two subtrees, so
1 + max(left, right). - Brute force walks every root-to-leaf path separately, re-counting shared upper nodes: up to O(n·h). The recursion answers each subtree once and reuses it: O(n).
- Answers flow upward (post-order). A node can only return after both children have, so badges fill in from the leaves to the root. The stack holds one frame per level: O(h) space.
- Pitfall: the base case must return 0 for null, not 1 for a leaf only. A node with one child still has a null child, and
maxsafely ignores its 0. (Minimum Depth is the trap: thereminwould pick that 0.) - Iterative BFS: run the level-order loop from problem 102 and count the levels. Iterative DFS: a stack of node and depth pairs, keeping the largest depth seen. Both O(n), and no
StackOverflowErroron a very deep tree.