CMD Guide
HomeDSATrees

Introduction to Tree Breadth First Search Pattern

Tree BFS solves any "level by level" question by pushing nodes into a FIFO queue in the order they're discovered, so a node is never processed before any node closer to the root — the queue's insertion order is the level order, because a node's children are enqueued only after the node itself has been dequeued.

Recognize the pattern

Brute force vs optimal

Brute force: recursive DFS that tracks depth and appends each value into a List<List<Integer>> indexed by depth. Correct, but it recomputes the level from a passed-in depth parameter and needs care to pre-size the outer list dynamically; for pure "level order" style problems (widths, right-side view, min depth) it also loses the natural queue boundary between levels, making early termination (e.g. minimum depth) awkward — you must fully explore before knowing the level count. Cost: O(n) time, O(h) extra recursion stack (h = height).

Optimal (iterative BFS): use a queue, and snapshot queue.size() at the start of each round to know exactly how many nodes belong to the current level before enqueuing their children. This makes level boundaries explicit and lets you short-circuit the moment a level-based condition is met (e.g. minimum depth stops at the first leaf found). Cost: O(n) time, O(w) space where w is the maximum level width.

Complexity from first principles

Every node is enqueued exactly once and dequeued exactly once — 2n queue operations — so total work is O(n) time. Each operation is O(1): a linked-list-backed queue (e.g. Java's LinkedList used as a Queue) gives O(1) worst-case per operation, while an array-backed circular-buffer queue gives O(1) amortized per operation (occasional resize).

The queue never holds more nodes than exist on the single widest level, because a level's nodes are fully drained before their children (the next level) are pushed; hence O(w) space, where w = max nodes at any depth. This bound depends entirely on shape: a completely skewed tree (every node has at most one child) is the best case for space — the queue never holds more than one node at a time, so O(1) space. A complete binary tree is the worst case — its bottom level alone holds about n/2 nodes, so O(n) space. Both are the same O(n) time, but they sit at opposite ends of the space spectrum.

Worked example

Problem: sum all node values in the tree [10, 5, 3, 7, null, null, 9] (root 10; left child 5; right child 3; 5's left child 7; 3's right child 9).

StepQueue beforeNode poppedSum afterQueue after (children pushed)
1[10]1010[5, 3]
2[5, 3]515[3, 7]
3[3, 7]318[7, 9]
4[7, 9]725[9]
5[9]934[]

Queue empties with sum = 34, matching the expected output.

Pitfalls

When to use / when not — trade-offs vs DFS

Use BFS when the problem is inherently level-shaped (level order, level averages, zigzag, right-side view) or needs the shortest path / minimum depth in an unweighted tree or graph, since BFS guarantees the first time you reach a target it's via the fewest edges. A telltale variant is "all nodes at distance K from a given target node" (LeetCode 863): the trick is that a tree edge only points parent→child, so first do one DFS/BFS pass to build a child → parent map, then run BFS outward from the target treating each node's neighbors as {left, right, parent} — after K levels of that BFS, the queue holds exactly the answer. It is still BFS-for-shortest-hops; you just repaired the tree into an undirected graph first.

Prefer DFS when the problem is path- or subtree-shaped (root-to-leaf sums, diameter, LCA, subtree aggregates) — DFS's O(h) space beats BFS's O(w) space on wide, shallow trees, and recursion maps directly onto path accumulation without extra bookkeeping.

Trade-off in one line: BFS spends O(w) space to get level structure and shortest-path guarantees for free; DFS spends O(h) space and gets natural path/subtree composition for free.

Java: level-order sum (queue-size snapshot idiom)

int sumTree(TreeNode root) {
    if (root == null) return 0;
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    int sum = 0;
    while (!queue.isEmpty()) {
        int levelSize = queue.size(); // freeze current level's count
        for (int i = 0; i < levelSize; i++) {
            TreeNode node = queue.poll();
            sum += node.val;
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }
    }
    return sum;
}

Takeaways

Recall: Why does snapshotting queue.size() before the inner loop matter, and what breaks if you skip it?

Play with it

Step through BFS level-order yourself — press Play and predict each fork:


Pattern derived from standard BFS/level-order traversal technique; problem instance adapted from the source binary-tree-sum walkthrough.

🤖 Don't fully get this? Learn it with Claude

Stuck on Introduction to Tree Breadth First Search Pattern? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.

🎨 Explain it visually

Build the mental picture, not memorization.

I just read a lesson on **Introduction to Tree Breadth First Search Pattern** (DSA) and want to truly understand it. Explain Introduction to Tree Breadth First Search Pattern from first principles using ONE vivid real-world analogy and a visual mental model — draw it as ASCII art or a clear step-by-step diagram — with a concrete example using real numbers. Then ask me one question to check I got the mental picture, and wait for my reply. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🤔 Walk me through it (interactive)

Socratic — adapts to where you're stuck.

Teach me **Introduction to Tree Breadth First Search Pattern** interactively. Ask me ONE guiding question at a time, wait for my answer, and adapt to my confusion — build the idea with me step by step instead of explaining it all at once. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧪 Quiz me & fix my gaps

Active recall exposes what you missed.

Quiz me on **Introduction to Tree Breadth First Search Pattern** with 5 questions, easy to tricky, ONE at a time. Tell me if each answer is right; at the end, explain clearly what I got wrong and why. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
🧠 Make it stick

Intuition + hook + flashcards for long-term memory.

Help me remember **Introduction to Tree Breadth First Search Pattern** for the long term: give the one-sentence intuition, a memorable hook/mnemonic, a tiny worked example, and 3 active-recall flashcards (Q -> A). If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.

📝 My notes