0

Tree BFS (level order)

Process the queue one full level at a time by snapshotting its length before the loop.

TreesO(n) time, O(width) spaceNew10 problems
18
mastery

Trigger phrases

If a problem statement sounds like one of these, try this pattern first.

level order
right side view
minimum depth
zigzag

The template

Get this into muscle memory, then adapt the condition per problem.

const q = [root];
while (q.length) {
  const size = q.length;
  for (let i = 0; i < size; i++) {
    const node = q.shift()!;
    if (node.left) q.push(node.left);
    if (node.right) q.push(node.right);
  }
}
Watch Level Order Traversal

If you are stuck

The generic hint ladder for this pattern, in order.

  1. 1The problem mentions levels or depth, so think queue, not recursion.
  2. 2Capture the queue length before processing to isolate one level.
  3. 3The last node of each level gives the right side view.

Drill it

Every problem in the bank that uses this pattern.

0 / 10 solved
1
2
3
4
5
6
7
8
9
10

Other patterns in Trees