Measure the longest root-to-leaf path in a binary tree by counting its nodes.
Problem
Input. The root of a finite binary tree with val, left, and right fields.
Output. Return the greatest number of nodes on any path from the root to a leaf.
Rules. Count nodes, not edges. A leaf has depth one and an empty tree has depth zero. Assume no shared nodes or cycles. Leave node values and child links unchanged.
Example. A root 3 has children 9 and 20; node 20 has children 15 and 7.
Return 3, for either path 3 -> 20 -> 15 or 3 -> 20 -> 7.
Its compact level-order notation is [3, 9, 20, null, null, 15, 7].
Picture
Each child sends one number upward, not its whole path.
Leaves 9, 15, and 7 each return 1.
Node 20 combines 1 and 1 into 2; root 3 combines 1 and 2 into 3.
Problem trace
Separate returned heights: extend the longer child path
Reference drawing
Problem trace
Add the current node to the larger returned child depth
Execution trace
- 3call max_depth(3)
- 9
- 20
- 15
- 7
- node 3
- call max_depth(3)
- call stack
- [3]
- known returns
- none
- 3
- 9return 1
- 20
- 15
- 7
- node 9
- not shown→return 1
- node 3
- call max_depth(3)→not shown
- call stack
- [3]→[3,9]
- 3
- 9
- 20
- 15return 1
- 7return 1
- node 15
- not shown→return 1
- node 7
- not shown→return 1
- node 9
- return 1→not shown
- 3
- 9
- 20return 2
- 15left 1
- 7right 1
- node 20
- not shown→return 2
- node 15
- return 1→left 1
- node 7
- return 1→right 1
- 3return 3
- 9left 1
- 20right 2
- 15
- 7
- node 3
- not shown→return 3
- node 9
- not shown→left 1
- node 20
- return 2→right 2
- Recognize it
- Use this pattern when a tree property for a node can be computed only after both child subtrees return summaries, especially height, diameter contributions, or root-to-leaf aggregates.
- Keep true
- Whenever max_depth(node) returns d, d is exactly the number of real nodes on the longest path from node to a leaf; max_depth(None) returns 0, making a leaf return 1.
- Reuse it
- Define the null identity first, ask each child for the smallest sufficient summary, and combine those summaries once; the same postorder fold supports subtree size, height, and path calculations.
Every path through a real node uses that node, then at most one child path. Therefore its node-count height is:
The returned number is the exact height of that subtree. Node values do not enter the recurrence.
Code
def max_depth(root: TreeNode | None) -> int:
if root is None:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))
Each node is visited once: time and recursive stack space.
A chain has , not .
Python can raise RecursionError on a deep tree before the mathematical computation finishes.
Failure Check
Counting edges changes the convention: the source tree has two edges on its longest path, but three nodes.
Using addition instead of max answers a different question: it returns 5 for this tree.
Change the Execution
New task: Trees can exceed Python’s recursive call limit.
Picture and change: Carry (node, depth) work items explicitly.
best is the greatest depth among nodes already removed from the stack.
def max_depth_iterative(root):
stack = [] if root is None else [(root, 1)]
best = 0
while stack:
node, depth = stack.pop()
best = max(best, depth)
if node.left is not None:
stack.append((node.left, depth + 1))
if node.right is not None:
stack.append((node.right, depth + 1))
return best
Check: The source tree still returns 3; an empty tree returns 0.
This uses time and auxiliary space on a binary tree.
It removes recursive calls, not memory needs or the no-cycle assumption.
Use when: Execution depth changes but the requested height does not.
Change the Aggregate
New task: Count every node, not one longest path.
Picture and change: Both child contributions now matter, so replace max with addition.
The returned fact becomes subtree size.
def tree_size(root):
if root is None:
return 0
return 1 + tree_size(root.left) + tree_size(root.right)
Check: The source tree has size 5 and height 3.
Empty and singleton trees have sizes 0 and 1.
Time remains , with recursive stack space and the same recursion limit.
Use when: All descendants contribute to the result.
Transfer Check
Why does the parent not need the actual longest path?
Answer
The output requests only a length. The larger child height contains everything needed for that scalar result. Returning the path itself would require a different summary.
Compare level-order traversal when the task requires whole levels rather than one returned height.