You met binary search trees in Part 8 and BFS vs DFS in Part 9. Now we turn them into the patterns that crack tree interview questions. The secret: nearly every tree question uses one of just two moves.
The 12 interview patterns: you are here
- 1Two Pointerssorted + pair
- 2Sliding Windowcontiguous subarray
- 3Prefix Sum + Hash Maprange sums, sum = K
- 4Binary Search on Answersmallest value that works
- 5Fast & Slow Pointerscycle, middle
- 6Merge Intervalsoverlapping ranges
- 7Monotonic Stacknext greater element
- 8Heap / Top-Ktop K, Kth largest
- 9Tree Patternsdepth, paths, levels
- 10Grid BFS & Topological Sortislands, dependencies
- 11Backtrackingall combinations
- 12DP Patternscount ways, min cost
The family tree story
To find how many generations a family has, the grandparent asks each child “how many generations under you?”, takes the bigger answer and adds one. That's DFS. To meet the family generation by generation (grandparents, then parents, then children), you go level by level. That's BFS. Try both on the same tree:
🌳 Go deep or go wide?
DFS starts at the root and always goes left first, as deep as it can.
DFS (a stack or recursion) dives down one branch before backing up: great for depth, paths and “check every subtree”. BFS (a queue) sweeps level by level: great for “level order”, “right side view” or the shortest path in steps. This tree's depth is 4.
DFS: trust your children
For DFS, don't trace the whole tree in your head. Assume the recursive calls on the left and right children already work, and only decide how to combine their answers at the current node:
- Max depth: 1 + max(left, right).
- Same tree / symmetric: values match and both pairs of children match.
- Path sum: subtract this node's value and ask the children for the rest.
- Valid BST: pass the allowed (min, max) range down to each child.
🔍 Use tree DFS / BFS when you see
- ✓The input is a binary tree (or BST)
- ✓Depth, height, diameter, balanced, symmetric
- ✓Paths and sums from root to leaf
- ✓“Level by level”, “right side view”, “minimum depth”
🚫 Don't use it when
- ✗A grid or a network with cycles (graph BFS/DFS with a seen-set)
- ✗Top K items (heap)
- ✗Plain arrays with pairs or windows
The two templates
def dfs(node):
if node is None: return BASE # empty tree
left, right = dfs(node.left), dfs(node.right)
return COMBINE(node, left, right) # e.g. 1 + max(left, right)
queue = [root]
while queue:
for _ in range(len(queue)): # exactly one level
node = queue.pop(0); visit(node)
add node.left, node.right if they exist⚡ Memory tricks
- 1
“Deep = DFS = stack. Wide = BFS = queue.”
Recursion is a hidden stack.
- 2
“Trust your children”
Write how to combine left and right answers; the recursion handles the rest.
- 3
“Empty tree first”
Every DFS starts with the base case for null.
- 4
“Freeze the queue size”
Read len(queue) at the start of a level to process exactly that level.
Code: max depth (DFS) and level order (BFS)
Outputs in the comments come from running the code.
from collections import deque
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def max_depth(root):
"""DFS: depth = 1 + the deeper of my two children."""
if root is None:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))
def level_order(root):
"""BFS: visit the tree level by level with a queue."""
levels, queue = [], deque([root] if root else [])
while queue:
level = []
for _ in range(len(queue)): # everyone on this level
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
levels.append(level)
return levels
# 3
# / \
# 9 20
# / \
# 15 7
root = Node(3, Node(9), Node(20, Node(15), Node(7)))
print(max_depth(root)) # 3
print(level_order(root)) # [[3], [9, 20], [15, 7]]One pattern, many problems
| Famous problem | How the pattern solves it | Level |
|---|---|---|
| Maximum Depth of Binary Tree | DFS: 1 + max(left, right) | Easy |
| Invert Binary Tree | DFS: swap children, recurse | Easy |
| Path Sum | DFS: subtract and pass down | Easy |
| Binary Tree Level Order Traversal | BFS, one level at a time | Medium |
| Binary Tree Right Side View | BFS, keep the last of each level | Medium |
| Validate Binary Search Tree | DFS with (min, max) range | Medium |
| Lowest Common Ancestor | DFS: both sides found → this node | Medium |
| Diameter of Binary Tree | DFS: left height + right height at each node | Easy |
🎯 Spot the pattern: is it tree DFS / BFS?
In an interview nobody tells you the pattern. Read each problem and decide. Look for the signal words.
1. Return what you'd see looking at a binary tree from its right side.
2. Check whether a binary tree is a valid binary search tree.
3. Find the kth largest number in an unsorted array.
4. Find the lowest common ancestor of two nodes.
5. Count the islands in a grid of land and water.
🧠 PATH memory card
Remember tree patterns for good
Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.
- P
Picture it
Your brain remembers scenes far better than definitions.
← swipe to see the whole picture →
A family tree: DFS asks each child how many generations are below them; BFS meets the family one generation at a time.
- A
Anchor it
A silly sentence you can't forget, where every word maps to the concept.
“Family tree: ask your children (DFS) or meet each generation (BFS)”
- Ask your children→DFS: combine left and right answers at each node
- Empty chair→Base case: a null node returns 0 / true / nothing
- Meet each generation→BFS: a queue, one level at a time
- Freeze the count→Read the queue size before processing a level
- T
Trace it
Run it by hand on a tiny example once. Doing beats reading.
Tree3 → (9, 20 → (15, 7)). DFS depth: 9 says 1, 15 and 7 say 1, so 20 says 2, so 3 says 1 + max(1, 2) = 3. BFS: [3] → [9, 20] → [15, 7]. - H
Hit-recall it
Test yourself now, then again on the day each card comes back.
Card 1 / 6 · new0 mastered · 0 practisedSay the answer out loud first, then flip and be honest.
Common mistakes
- Forgetting the null check. Every recursive tree function needs a base case for an empty node.
- Checking a BST only against direct children. A node must fit the range set by all its ancestors.
- Mixing levels in BFS. Freeze the queue size before the inner loop.
Where to go next
Trees have no cycles and one root. Grids and networks have neither, so you need a “seen” set, and sometimes an order of tasks: grid BFS and topological sort.
Key takeaways
- ✓Most tree questions use DFS (deep) or BFS (wide).
- ✓DFS: trust your children, then combine their answers; handle null first.
- ✓BFS: a queue, processing one level (the frozen queue size) at a time.
- ✓Both are O(n); DFS uses O(height) space, BFS O(width).
- ✓Signals: depth, paths, valid BST, LCA (DFS); level order, right view (BFS).
Frequently asked questions
What are the main binary tree patterns for interviews?
Almost every tree question is one of two moves. DFS (depth-first, usually recursion) for depth, paths, sums, 'is it balanced / valid / symmetric' and lowest common ancestor. BFS (breadth-first, with a queue) for anything level by level: level order, right side view, minimum depth, zigzag.
How do I solve tree problems with recursion?
Trust the recursion. Ask: if my left and right children already gave me their answers, how do I combine them for this node? Then handle the empty tree (base case). Max depth is 1 + max(left, right); a valid BST passes allowed ranges down; path sum subtracts the node's value as you go down.
When should I use BFS instead of DFS on a tree?
Use BFS when the question mentions levels: 'level order', 'each level', 'rightmost node of each level', or the minimum depth (BFS finds the shallowest leaf first). Use DFS for everything about paths and subtrees.
What is the lowest common ancestor (LCA)?
The deepest node that has both given nodes in its subtree. With DFS: if the current node is one of them, return it; otherwise ask both children. If both sides return something, the current node is the LCA; if only one does, pass that one up.
What's the time and space complexity of tree DFS and BFS?
Both visit every node once: O(n) time. DFS uses O(h) space for the recursion (h = height, up to n for a skewed tree). BFS uses O(w) space for the queue, where w is the widest level.
🧠 Quick check: tree patterns
1. “Return the values of the tree, level by level.” Which approach?
2. Max depth: left subtree depth 2, right subtree depth 4. Depth of this node?
3. In BFS level order, how do you know where one level ends?
4. What's the base case for most tree recursions?
Checking your access…