3.4.3Trees

Level-order traversal — BFS with queue

2,092 words10 min readdifficulty · medium1 backlinks

What it is


HOW it works — derive the algorithm from scratch

Start from the requirement: visit floor 0, then floor 1, then floor 2…

  1. We can only "see" a node's children once we process that node. So we need to remember nodes we've discovered but not yet processed.
  2. We must process them in discovery order (root first, then root's children left→right, etc.). That ordering demand = FIFO = a queue.
  3. So the recipe writes itself:
Figure — Level-order traversal — BFS with queue

Getting one list per level (level grouping)

Plain BFS gives a flat list. To group by level, snapshot the queue size at the start of each round — that size is exactly the count of nodes on the current level.


Complexity — reasoned, not memorized

  • Time O(n)O(n): each node is enqueued exactly once and dequeued exactly once. Constant work per node ⇒ linear total.
  • Space O(w)O(w) where ww is the maximum width (most nodes on any single level). Worst case the bottom level of a complete tree holds n/2\approx n/2 nodes ⇒ O(n)O(n).

Worked examples



Recall Feynman: explain to a 12-year-old (click to reveal)

Picture a family tree drawn on a wall. You want to read out names one row at a time, left to right. You hold a line of people waiting (a queue). You call the first person in line, write their name, and tell them: "send your kids to the BACK of the line." Then you call the next person in line. Because new kids always go to the back, you finish reading a whole row before any kid from that row gets called. That's level order — and the waiting line is the queue!


Active recall

What data structure makes level-order traversal natural, and why?
A queue (FIFO); it serves nodes in discovery order so closer/leftmost nodes are processed first, producing level-by-level order.
Why does using a stack instead of a queue break level-order traversal?
A stack is LIFO, so it dives into the most recently added (deepest) node first — that yields depth-first order, not level order.
In grouped (level-by-level) BFS, why must you snapshot len(queue) before the inner loop?
Because the queue grows as you enqueue children; freezing the count fences off exactly the current level's nodes so you don't spill into the next level.
What is the time complexity of BFS on a tree and why?
O(n)O(n) — each node is enqueued once and dequeued once with O(1)O(1) work each.
What is the space complexity of BFS and what determines it?
O(w)O(w) where ww is the maximum level width; worst case O(n)O(n) (bottom level of a complete tree ≈ n/2 nodes).
Why is list.pop(0) a bad queue for BFS in Python?
It is O(n)O(n) (shifts all elements), degrading BFS to O(n2)O(n^2); use collections.deque.popleft() for O(1)O(1).
On a tree, how is BFS related to "distance from root"?
Level/depth equals distance from root, so BFS (which expands by increasing distance) visits nodes in level order.
What guard prevents a crash when a node lacks a child during BFS?
Check if node.left / if node.right (or skip None) before enqueuing/dereferencing.

Connections

  • Breadth-First Search (BFS) — the general graph algorithm; level-order is its tree special case.
  • Depth-First Search (DFS) — the stack/recursion counterpart (pre/in/post-order).
  • Queue (FIFO) data structure — the engine of BFS; contrast with Stack (LIFO).
  • Binary Tree representation — nodes with .left / .right.
  • Shortest path in unweighted graphs — BFS's killer app; level = hop count.
  • Tree height vs width — explains the DFS-stack vs BFS-queue space trade-off.

Concept Map

is exactly

expands by distance

needs to

must keep

demands FIFO

enables

dequeue oldest gives

freeze n before loop

fences levels

each node once

Level-order traversal

Breadth-First Search

Queue FIFO

Visit floor by floor

Remember discovered nodes

Process in discovery order

BFS-with-queue procedure

Snapshot queue size n

One list per level

Time O of n

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, Level-order traversal ka matlab hai tree ko floor by floor padhna — sabse upar root, fir uske niche wale bachche, fir unke bachche. Yeh exactly BFS hai. Iske liye hum queue use karte hain kyunki queue FIFO hai: jo pehle line mein aaya, woh pehle serve hota hai. Isi wajah se upar wale aur left wale nodes pehle process hote hain aur output sahi order mein aata hai.

Algorithm bilkul simple hai: root ko queue mein daalo. Jab tak queue khaali na ho — front se node nikaalo (dequeue), use visit karo, aur uske left aur right child (agar exist karte hain) ko queue ke peeche daal do. Bas! Kyunki naye bachche hamesha peeche jaate hain, ek poora level khatam hone se pehle agle level ka koi node process nahi hota. Agar tumhe har level ki alag list chahiye, to inner loop se pehle n = len(queue) snapshot le lo — yahi current level ke nodes ki ginti hai, aur tum theek utni baar loop chalao.

Do badi galtiyan yaad rakhna: (1) Stack mat use karna queue ki jagah — stack LIFO hai, woh deep chala jayega aur DFS ban jayega, level order nahi. (2) Python mein list.pop(0) mat use karna kyunki woh O(n)O(n) hai aur poora BFS O(n2)O(n^2) ho jata hai; iski jagah collections.deque ka popleft() use karo jo O(1)O(1) hai.

Complexity samajhna easy hai: har node ek baar andar, ek baar bahar — isliye time O(n)O(n). Space queue ke max size par depend karta hai, jo tree ki maximum width (ww) hota hai. Yaad rakho: DFS stack ek path (height) rakhta hai, BFS queue ek level (width) rakhta hai — yahi dono ka basic trade-off hai. BFS unweighted graph mein shortest path nikalne ke liye bhi sabse zaroori tool hai, isliye yeh concept pakka karna.

Go deeper — visual, from zero

Test yourself — Trees

Connections