← Trees
Problem
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.
Signal
"How deep does this tree go" is the base recursive shape everything else in this pattern builds on: a node's depth is 1 plus the deeper of its two children's depths, bottoming out at 0 for an empty subtree.
Approach
Recursively compute the depth of the left and right subtrees, return
1 + max(left, right). An empty node has depth 0.
Skeleton
def depth(node):
if not node: return 0
return 1 + max(depth(node.left), depth(node.right))
Solution
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def max_depth(root: TreeNode | None) -> int:
if root is None:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))
Complexity
O(n) time — every node visited once. O(h) recursion stack space.
Pitfalls
- Depth counts nodes, not edges — a single-node tree has depth 1, not 0; don't confuse this with diameter, which counts edges.
- Deep, skewed trees (a long chain of single-child nodes) can hit Python's recursion limit; an iterative BFS level-count avoids that if it comes up.