SproutStackSproutStack home

Trees: BFS & DFS

7 min readBeginner-friendlyFree to read

Read a little, play a little. No scary maths, and no rush.

Share:

Family trees that compute

A tree is a root with children, each child a smaller tree — org charts, file systems, DOMs, decision flows. No cycles, so no visited-set bookkeeping: the two ways to walk one cover most tree interviews.

DFS: depth first, recursion's home turf

Dive down one branch completely before trying siblings. Maximum depth falls out naturally — an empty tree has depth 0, anything else is one plus the deeper subtree:

def max_depth(r):
    if not r:
        return 0
    return 1 + max(max_depth(r.left), max_depth(r.right))

DFS flavors (inorder/preorder/postorder) differ only in when you visit the node versus its children — inorder of a binary search tree yields sorted order, a favorite follow-up fact.

BFS: level by level with a queue

Breadth-first visits floor by floor — perfect for "level order" output and shortest paths in unweighted graphs. The pattern: process exactly len(queue) nodes per level before moving down:

from collections import deque

def levels(r):
    q, out = deque([r]), []
    while q:
        out.append([n.v for n in q])
        for _ in range(len(q)):   # freeze the level size first!
            n = q.popleft()
            if n.left:
                q.append(n.left)
            if n.right:
                q.append(n.right)
    return out

Snapshotting len(q) before the inner loop is the detail that makes levels work — without it, levels blur together.

A level-order trace

For a tree with root 1, whose children are 2 and 3, where 2 has children 4 and 5:

  • The queue holds [1]. Freeze size 1, take 1, add 2 and 3. Level: [1].
  • The queue holds [2, 3]. Freeze size 2, take both, adding 4 and 5. Level: [2, 3].
  • The queue holds [4, 5]. Freeze size 2, take both, no children. Level: [4, 5].

Result: [[1], [2, 3], [4, 5]].

Choosing a DFS order

  • Preorder (node, then children) suits copying or saving a tree, because each parent is recorded before its children.
  • Inorder (left, node, right) on a binary search tree returns the values in sorted order.
  • Postorder (children, then node) suits anything computed from the children first, such as subtree sizes, heights, or safely deleting a tree.

Binary search trees in one paragraph

A binary search tree keeps every value in the left subtree smaller than the node and every value in the right subtree larger. Searching compares and goes left or right, so it costs O(height). In a balanced tree the height is about log n; in a tree built from already-sorted input without balancing, it degrades into a chain and every operation becomes O(n).

Iterative DFS for very deep trees

Recursion uses the call stack, and Python stops at about 1,000 levels by default. For a tree that might be extremely deep, use your own stack: push the root, then repeatedly pop a node, process it, and push its children. Same traversal, no depth limit.

Common tree mistakes

  • Forgetting the empty tree. Every recursive function needs the if not node case first.
  • Confusing depth and height. Depth counts down from the root; height counts up from the leaves. Say which one you mean.
  • Assuming the tree is balanced. Unless the problem says so, plan for the worst case, where the height equals the number of nodes.
  • Mixing up levels in BFS. Freeze the level size before the inner loop, as shown above.

Remember this

  • Depth/diameter/path questions → DFS recursion. Levels/shortest → BFS queue.
  • Empty-tree base case first, always; null checks are where tree solutions die.

Check your understanding

5 questions · first-try answers earn the most XP

1. Why does maximum tree depth come out naturally from DFS recursion?
2. Why does an inorder traversal of a binary search tree visit the values in sorted order?
3. Why does the level-order BFS freeze `len(queue)` before its inner loop?
4. Which tree problem is a poor fit for recursion?
5. Why don't tree algorithms need a visited set?

My notes

Saved in this browser. Highlight a line above and save it, or write it in your own words.

Nothing saved yet. Your highlights will live here.

References

Finished reading?

Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.

Related chapters

Practice this pattern elsewhere

More problems to practise on external judges. Both links open the site home rather than a specific set, so you can pick problems for this pattern.

Spotted a mistake or want a topic covered? Report an issue

📬 An occasional email when new lessons land

New lessons and showdowns, no more than a few times a month. No spam, unsubscribe anytime. We store your email only to send the newsletter.