4. Linked Lists, Trees & Heaps
Binary Trees: Recursive DFS & Level-Order BFS
Think recursively on trees: understand preorder, inorder, and postorder DFS traversals, compute tree height and diameter, and traverse level-by-level with a deque BFS queue.
- Write clean recursive DFS tree functions in 4–6 lines using base cases on None
- Distinguish preorder, inorder, and postorder traversals
- Traverse a tree level by level in O(n) time using collections.deque
Trees look intimidating until you realize a tree is recursive by definition: every node is simply the root of a smaller left subtree and a smaller right subtree. Unlike graphs, binary trees have no cycles, so you never need a visited set!
Why It Matters: Thinking in Subtrees Instead of Whole Trees
A naive beginner tries to trace every branch mentally from the root to the leaves and gets lost after 3 levels. Recursive Depth-First Search (DFS) flips that around: assume dfs(node.left) and dfs(node.right) already return the right answers for the left and right subtrees, then combine them at node!
Every node is visited once → O(n) time and O(h) space (where h is tree height: O(log n) for balanced trees, O(n) worst-case for a skewed chain).
Pattern 1: Recursive DFS & Traversal Orders
Preorder visits root first, Inorder visits left→root→right (sorted on BSTs!), Postorder resolves children first, and BFS visits depth-by-depth.
Ask two questions for almost every tree DFS problem:
- Base case: What should I return if
node is None? (0for depth/sum,Truefor validity,Nonefor inverting). - Combine: Given
left_ansandright_ans, how do I computenode's answer?
def max_depth(root) -> int:
if not root:
return 0
return 1 + max(max_depth(root.left), max_depth(root.right))The 3 DFS Orders (Preorder, Inorder, Postorder)
| Traversal | Visit Order | Classic Interview Use Cases |
|---|---|---|
| Preorder | node → left → right | Copying/serializing a tree, passing path/bounds top-down |
| Inorder | left → node → right | Yields sorted values on a Binary Search Tree! |
| Postorder | left → right → node | Computing heights, diameters, subtree sums bottom-up, deleting nodes |
Dry-Run Trace: max_depth on 4 -> (2 -> (1, 3), 7 -> (None, 9))
| Call | Node Val | Left Result | Right Result | Returned Value (1 + max(L, R)) |
|---|---|---|---|---|
max_depth(1) | 1 | 0 | 0 | 1 |
max_depth(3) | 3 | 0 | 0 | 1 |
max_depth(2) | 2 | 1 | 1 | 1 + max(1, 1) = 2 |
max_depth(9) | 9 | 0 | 0 | 1 |
max_depth(7) | 7 | 0 | 1 | 1 + max(0, 1) = 2 |
max_depth(4) | 4 | 2 | 2 | 1 + max(2, 2) = 3 |
Pattern 2: Level-Order BFS (collections.deque)
When a problem asks for level-by-level output (zigzag levels, right-side view) or minimum depth (nearest leaf), use Breadth-First Search (BFS) with collections.deque:
def level_order(root) -> list[list[int]]:
if not root:
return []
q = deque([root])
levels = []
while q:
level = []
for _ in range(len(q)): # Snapshot current level width!
node = q.popleft()
level.append(node.val)
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
levels.append(level)
return levelsStep-by-Step BFS Trace on the Same Tree
| Level | len(q) Snapshot | Popped Nodes | Enqueued Children | levels After Turn |
|---|---|---|---|---|
| 0 | 1 | 4 | 2, 7 | [[4]] |
| 1 | 2 | 2, 7 | 1, 3, 9 | [[4], [2, 7]] |
| 2 | 3 | 1, 3, 9 | None | [[4], [2, 7], [1, 3, 9]] |
Edge Cases to Always Check
- Empty tree (
root is None): DFS base cases return0/None; BFS checksif not root: return []BEFOREdeque([root])(otherwise[None]is truthy and crashes onnode.val!). - Single-node tree:
max_depthreturns1;level_orderreturns[[root.val]]. - Skewed tree (
1 -> 2 -> 3 -> ... -> 1000): Recursive DFS takesO(n)call stack; BFS space isO(1)at width1(whereas on a full balanced tree, BFS queue holds up ton / 2leaf nodes →O(n)space!).
In invert_tree, writing root.left = invert_tree(root.right) followed by root.right = invert_tree(root.left) on separate lines overwrites root.left before you read it! Always use Python's simultaneous tuple assignment: root.left, root.right = invert_tree(root.right), invert_tree(root.left).
Pick DFS for path sums, tree height/diameter, subtree validation, and lowest common ancestor. Pick BFS for level-by-level grouping, right-side view, or shortest distance to a leaf.
Try It Yourself in the Playground
Run Max Depth, Diameter of Binary Tree (Postorder DFS), Invert Tree, and Level-Order BFS below:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Why do we capture for _ in range(len(q)): at the top of the while q: loop in level_order?
Quick Checkpoints
Which DFS traversal order processes child subtrees BEFORE the parent node (useful for computing heights or subtree sums)?
Which Python data structure gives O(1) popping from the front during Breadth-First Search (BFS)?
In level_order(root), why must we write if not root: return [] before creating q = deque([root])?