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.

6 min readUpdated 2026-11-30
In This Lesson
  • 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

Binary Tree DFS Orders vs Level-Order BFS
427139
Preorder: [4, 2, 1, 3, 7, 9]
Inorder (Sorted!): [1, 2, 3, 4, 7, 9]
Postorder: [1, 3, 2, 9, 7, 4]
Level BFS: [[4], [2, 7], [1, 3, 9]]

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:

  1. Base case: What should I return if node is None? (0 for depth/sum, True for validity, None for inverting).
  2. Combine: Given left_ans and right_ans, how do I compute node's answer?
python
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)

TraversalVisit OrderClassic Interview Use Cases
Preordernode → left → rightCopying/serializing a tree, passing path/bounds top-down
Inorderleft → node → rightYields sorted values on a Binary Search Tree!
Postorderleft → right → nodeComputing heights, diameters, subtree sums bottom-up, deleting nodes

Dry-Run Trace: max_depth on 4 -> (2 -> (1, 3), 7 -> (None, 9))

CallNode ValLeft ResultRight ResultReturned Value (1 + max(L, R))
max_depth(1)1001
max_depth(3)3001
max_depth(2)2111 + max(1, 1) = 2
max_depth(9)9001
max_depth(7)7011 + max(0, 1) = 2
max_depth(4)4221 + 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:

python
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 levels

Step-by-Step BFS Trace on the Same Tree

Levellen(q) SnapshotPopped NodesEnqueued Childrenlevels After Turn
0142, 7[[4]]
122, 71, 3, 9[[4], [2, 7]]
231, 3, 9None[[4], [2, 7], [1, 3, 9]]

Edge Cases to Always Check

  • Empty tree (root is None): DFS base cases return 0 / None; BFS checks if not root: return [] BEFORE deque([root]) (otherwise [None] is truthy and crashes on node.val!).
  • Single-node tree: max_depth returns 1; level_order returns [[root.val]].
  • Skewed tree (1 -> 2 -> 3 -> ... -> 1000): Recursive DFS takes O(n) call stack; BFS space is O(1) at width 1 (whereas on a full balanced tree, BFS queue holds up to n / 2 leaf nodes → O(n) space!).
Simultaneous Tuple Swap in invert_tree

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).

DFS vs BFS: Which Should You Pick?

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:

Python 3Try It Live: Binary Tree DFS & Level-Order BFS
Output

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

Check Your Understanding

Which DFS traversal order processes child subtrees BEFORE the parent node (useful for computing heights or subtree sums)?

Check Your Understanding

Which Python data structure gives O(1) popping from the front during Breadth-First Search (BFS)?

Check Your Understanding

In level_order(root), why must we write if not root: return [] before creating q = deque([root])?