Tree BFS (Level Order)
O(n)
Process the tree level by level with a queue, recording the size of each level before draining it.
0/10 solved
Recognise it
The signal
Anything per level: level order, averages, right-side view, zigzag, level width, or minimum depth / nearest leaf.
1Brute force
DFS with depth parameter and per-depth lists (works, but BFS is natural).
2The observation
Level grouping: the queue already holds exactly one level at a time.
3Why it works
At the start of each round, the queue holds exactly the nodes at the current depth.
Reach for it when
- +Level-order traversal, or anything computed per level (averages, max per level).
- +Right/left side view, zigzag, or minimum depth (BFS finds the shallowest leaf first).
- +Shortest path in an unweighted graph/tree (fewest edges).
Not when
- ×Root-to-leaf paths or a recursive subtree property (height, diameter)use Tree DFS
- ×Memory matters and the tree is bushy (BFS holds up to n/2 nodes)use DFS, O(height) space
- ×Weighted shortest pathuse Dijkstra, not plain BFS
Intuition
A binary tree is nodes with a .left and .right child. BFS = breadth-first = level by level: finish the whole top row before touching the next, like reading a page left-to-right, line by line. The engine is a queue (first-in-first-out): you take a node from the front, then push its children to the back — so children are always processed after everything on the current level.
Read the full intuition
The one trick that makes "level order" clean: snapshot the queue's size at the start of each level. That count is exactly how many nodes are on this level; drain exactly that many, collecting them into one list, and whatever you pushed (their children) becomes the next level.
Walk a tree 3 / (9, 20) / 20→(15,7):
- Queue=[3]. Level size 1 → pop 3, push 9,20. Level = [3].
- Queue=[9,20]. Size 2 → pop 9 (no kids), pop 20 (push 15,7). Level = [9,20].
- Queue=[15,7]. Size 2 → pop both. Level = [15,7]. Done.
Key idea
Any prompt with "level", "level order", "right-side view", "zigzag", or "minimum depth" is BFS. The level-size snapshot is the whole pattern.
Why it costs what it costs
Time O(n). each node is enqueued and dequeued exactly once.
Space O(w). the queue holds at most one level; the widest level can be up to n/2 nodes in a full tree.
Practice
- Binary Tree Level Order TraversalFoundationFoundationAmazon, MetaMedium
- Average of Levels in Binary TreeApply it · Aggregate per level.Apply itEasy
- Binary Tree Right Side ViewOne change · Keep only the last node per level.One changeMeta, AmazonMedium
- Binary Tree Zigzag Level Order TraversalOne change · Alternate direction.One changeAmazon, MicrosoftMedium
- Minimum Depth of Binary TreeTwists · Stop at the first leaf.TwistsEasy
- Maximum Width of Binary TreeBranches · Width includes null gaps.BranchesMedium
- Binary Tree Vertical Order TraversalBranches · Group by column, ordered by level.BranchesPremiumMedium
- All Nodes Distance K in Binary TreeCombine · Distance can go upward.CombineMeta, AmazonMedium
- Populating Next Right Pointers in Each NodeAdvanced · O(1) extra space.AdvancedMeta, MicrosoftMedium
- Vertical Order Traversal of a Binary TreeHard
Pitfalls
Classic bugs
- !Python
list.pop(0)/ JSq.shift()are O(n): usedeque.popleft(), or build the next level as a fresh array and swap. - !Reading
len(q)after pushing children: capture the level size before draining the level. - !No null-root check: an empty tree crashes. Return early.
- !Zigzag: keep child order the same and reverse the collected level list, don't flip traversal direction.
- !Min depth: stop at the first leaf (no children), not the first null child.
Go deepervariants and techniques · resources
Variants and techniques
- Level aggregatesCollect or reduce each level (sum/avg/max). Average of Levels, Largest Value per Row.
- Side viewsTake the last (or first) node of each level. Right Side View.
- ZigzagReverse alternate collected levels before appending. Zigzag Level Order.
- Minimum depth / shortestReturn the depth at the first leaf you dequeue. Minimum Depth of Binary Tree.