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).
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
Every node is enqueued and dequeued exactly once.
Queue holds at most one full level; W is the max width of the tree.
Step-by-step trace
| # | Action | Node | Level | Queue | Output so far |
|---|