Skip to content
TOPIC · 15 PROBLEMS · 4 PATTERNS

Trees

A root, and below it smaller trees of the same shape. Solve it for one node, trust the recursion for its children, and you have solved it for the whole tree.

How to spot a tree problem

“root”You are handed a TreeNode. Almost every answer is a short recursive function on that node and its two children.
“depth / level”Anything asked row by row, such as each level, the view from one side, or the shallowest leaf. That is breadth-first search.
“path”A path from the root down, or between any two nodes. Each node either passes something down or hands a best result back up.
“BST”A binary search tree. Smaller values go left and larger go right, so you can skip half the tree, and an in-order walk comes out sorted.

Four patterns cover almost everything

Bottom-up DFS

O(n)

Ask each child for its answer first, then combine the two into the answer for this node.

Reach for it when the answer for a node depends on its subtrees, such as height, balance or the best path below it.Go deeper: Pre-order, in-order and post-order, drawn

Top-down DFS

O(n)

Carry what you know so far down into each call, such as a running sum, the largest value above, or allowed bounds.

Reach for it when each node needs to know something about the path that led to it.Go deeper: Pre-order, in-order and post-order, drawn

Level-order BFS

O(n)

Use a queue and handle one level at a time by taking exactly as many nodes as the queue held when the level began.

Reach for it when the question is about rows: each level, the rightmost node, or the nearest leaf.Go deeper: BFS and DFS: same graph, different order

BST walk

O(h)

Compare with the current node and go left or right. Or walk in order to see the values sorted.

Reach for it when the tree is a binary search tree and the question is about order, ranges or the kth value.Go deeper: How a binary search tree stays searchable

The one template to memorise

A recursive function that returns a height and keeps a running best on the side. Diameter, balance and maximum path sum are all this shape.

solution.py
# Assumes a TreeNode with .left and .right.
def diameter(root):
best = 0
def height(node):
nonlocal best
if node is None:
return 0
left = height(node.left)
right = height(node.right)
best = max(best, left + right) # longest path that bends here
return 1 + max(left, right)
height(root)
return best

Problems, easy to hard

Do them in order the first time
Next upGraphsDynamic programming