← All patterns
15 / 32
Trees & Recursion

Tree BFS

When you see it

Signal words

If the prompt uses any of these, this pattern should come to mind first.

level orderby levelshortest depthright side viewzigzagper row
Practice

Drill this pattern with an AI trainer — reply only with Hint, Next, Lost, or paste your code.

Ask yourself

  1. Process tree level by level?
  2. Min depth / level totals / row views?
  3. Queue, capturing len(queue) per level.

Classic problem

Binary Tree Level Order Traversal (LeetCode 102) — return node values grouped by level. Snapshot the queue size before each level so you drain exactly one row at a time.

Input: root = [3, 9, 20, null, null, 15, 7]

Output: [[3], [9, 20], [15, 7]] — three levels, each drained in one queue pass.

Watch it run

Common pitfalls

Not snapshotting level size before the inner loop.

Enqueuing None children.