Return a binary tree’s values grouped by depth, with each level listed from left to right.
Problem
Input. The root of a finite binary tree whose nodes have a value and optional left and right children.
Output. Return one list of values per depth, starting with the root’s level.
Rules. Within each level, preserve the nodes’ left-to-right order.
Missing children contribute no output value or placeholder.
Assume no shared nodes or cycles. Leave the tree unchanged; an empty tree returns [].
Example. A root 3 has children 9 and 20; node 20 has children 15 and 7.
Return [[3], [9, 20], [15, 7]], not one flattened list.
Its compact level-order input notation is [3, 9, 20, null, null, 15, 7].
Picture
Imagine a boundary in the queue between this level and the children being added for the next. At each outer-loop start, the queue contains exactly one complete level. Capture its size before appending anything.
| Frozen size | Values removed | Queue after those removals |
|---|---|---|
1 | 3 | [9,20] |
2 | 9,20 | [15,7] |
2 | 15,7 | [] |
Problem trace
Freeze this level's queue length before adding the next level
- 3queued
- 9
- 20
- 15
- 7
- node 3
- queued
- queue state
- [3]
- answer
- []
- 3level [3]
- 9next queue
- 20next queue
- 15
- 7
- node 3
- queued→level [3]
- node 9
- not shown→next queue
- node 20
- not shown→next queue
- 3
- 91 of 2
- 202 of 2
- 15
- 7
- node 9
- next queue→1 of 2
- node 20
- next queue→2 of 2
- node 3
- level [3]→not shown
- 3
- 9level [9,20]
- 20level [9,20]
- 15next queue
- 7next queue
- node 9
- 1 of 2→level [9,20]
- node 20
- 2 of 2→level [9,20]
- node 15
- not shown→next queue
- 3
- 9
- 20
- 15level [15,7]
- 7level [15,7]
- node 15
- next queue→level [15,7]
- node 7
- next queue→level [15,7]
- node 9
- level [9,20]→not shown
- Recognize it
- Use this BFS form when a tree answer is grouped by depth, processed left-to-right by level, or must compute one aggregate per level rather than one flat visitation order.
- Keep true
- At each while-loop start, the queue contains exactly one complete next level in left-to-right order. Iterating the captured length consumes only that level while appending its children for the following level.
- Reuse it
- Capture the frontier size before expanding it whenever output or timing is grouped by BFS depth; this transfers to right-side view, level averages, shortest unweighted paths, and wave simulations.
Reference drawing
Problem trace
Freeze this level's queue length before adding the next level
Execution trace
- 3queued
- 9
- 20
- 15
- 7
- node 3
- queued
- queue state
- [3]
- answer
- []
- 3level [3]
- 9next queue
- 20next queue
- 15
- 7
- node 3
- queued→level [3]
- node 9
- not shown→next queue
- node 20
- not shown→next queue
- 3
- 91 of 2
- 202 of 2
- 15
- 7
- node 9
- next queue→1 of 2
- node 20
- next queue→2 of 2
- node 3
- level [3]→not shown
- 3
- 9level [9,20]
- 20level [9,20]
- 15next queue
- 7next queue
- node 9
- 1 of 2→level [9,20]
- node 20
- 2 of 2→level [9,20]
- node 15
- not shown→next queue
- 3
- 9
- 20
- 15level [15,7]
- 7level [15,7]
- node 15
- next queue→level [15,7]
- node 7
- next queue→level [15,7]
- node 9
- level [9,20]→not shown
- Recognize it
- Use this BFS form when a tree answer is grouped by depth, processed left-to-right by level, or must compute one aggregate per level rather than one flat visitation order.
- Keep true
- At each while-loop start, the queue contains exactly one complete next level in left-to-right order. Iterating the captured length consumes only that level while appending its children for the following level.
- Reuse it
- Capture the frontier size before expanding it whenever output or timing is grouped by BFS depth; this transfers to right-side view, level averages, shortest unweighted paths, and wave simulations.
During a level, the queue can mix unprocessed current nodes with already discovered next-level nodes. The captured count prevents consuming those children too early. Appending left before right preserves the requested order.
Code
This complete reference includes its node definition.
range(len(queue)) evaluates the length once, before the loop body changes the queue.
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass(eq=False, slots=True)
class TreeNode:
val: int
left: TreeNode | None = None
right: TreeNode | None = None
def level_order(root: TreeNode | None) -> list[list[int]]:
if root is None:
return []
answer: list[list[int]] = []
queue = deque([root])
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
answer.append(level)
return answer
Each node is queued and removed once: time. The queue uses auxiliary space, where is the widest level. It may hold parts of two adjacent levels, still within a constant multiple of . The returned lists separately occupy space.
Failure Check
Consuming until the queue empties inside one level also consumes newly appended children.
The source tree then collapses into [3,9,20,15,7], losing the depth partition.
Graph inputs need a separate discovered-state contract.
Select One Value
New task: Return the visible right-side value at each depth.
Picture and change: Keep the same depth partition, then select the final left-to-right value. Place this wrapper after the reference above.
def right_side_values(root):
return [level[-1] for level in level_order(root)]
Check: The source returns [3,20,7]; an empty tree returns [].
The wrapper still materializes all levels temporarily: peak storage, not just its returned values.
Use when: One selected value per level is enough.
Reduce Each Level
New task: Return one sum per depth.
Picture and change: Keep the partition and add each level’s values.
def level_sums(root):
return [sum(level) for level in level_order(root)]
Check: The source returns [3,29,22].
Negative and zero values also contribute normally.
Both wrappers take time and leave input links unchanged.
Both retain the reference’s temporary level materialization.
A fused version could accumulate within each frozen frontier instead.
Use when: Only an aggregate per level is required.
Transfer Check
Why not replace the FIFO queue with a stack while keeping this reasoning?
Answer
A stack can visit newly added descendants before remaining siblings. It does not preserve this complete next-depth frontier without additional state. Compare subtree heights for a different traversal contract.