← Queue / BFS

Pattern Recognition Drill

#39 — Level-order traversal (BFS)

Medium Trees

The Problem

Return the level-order traversal of a binary tree as list of lists.

What approach would you use?

Think about it before scrolling down.

Key Signals

Queue / BFS

Use a queue. Process one full level at a time using len(queue) at level start. O(n).

Alt: DFS / Recursion

DFS passing depth parameter, append to result[depth]. Works but less intuitive for 'level-order'.

Common Trap

Standard BFS doesn't group by level. The key trick: for each level, process exactly len(queue) nodes.

← #38 #40 →