Pattern / Tree BFS Queue · Level by Level Medium

Tree BFS — Level Order, Zigzag & Right Side View

One queue-driven sweep, three classic outputs: walk the tree level by level in — O(N) time, O(W) space

What does it solve?

Breadth-First Search visits a tree level by level using a queue. Push the root, then repeatedly pop a node and enqueue its children. The trick that unlocks every variant: at the top of each loop, snapshot the current queueSize. That count is exactly how many nodes sit on the current level, so you can process a whole level in one inner loop.

From that single skeleton you get three answers for free: Level Order (each level as its own list), Zigzag (alternate the direction per level), and Right Side View (the last node dequeued on each level).

// BFS skeleton — the level-size snapshot
q.push(root)
while q not empty:
  sz = q.size()  // nodes on this level
  for i in 0..sz:
    node = q.pop()
    // last i ⇒ right-side view
    push node.left, node.right
LC
Practice all three variants on LeetCode: Level Order (102), Zigzag (103), Right Side View (199).
Open Problem
Time Complexity
O(N)

Every node is enqueued and dequeued exactly once.

Space Complexity
O(W)

Queue holds at most one full level; W is the max width of the tree.

Live Visualization
Dequeued (current) In queue Picked for output Fully processed
Queue (front → back)
Output by level
node = – level = 0 dir = L→R visited = 0
Step 0 / 0
Current
–
dequeued node
Queue size
0
nodes waiting
Level
0
current depth
Visited
0
nodes emitted
Pick a mode and hit Play to sweep the tree level by level.
✓ Done Speed

Step-by-step trace

#ActionNodeLevelQueueOutput so far
C++ — Level Order (LC 102)

  

📝 My Notes ●

▾