Binary Tree Level Order Traversal
The problem
Return a binary tree’s values grouped by depth, from the root level downward and left to right within each level.
Example
Root 5 with children 2 and 9 → [[5], [2, 9]]
Need a hint?
Snapshot the queue size before processing a level.
Write pseudocode, trace the example, or note an edge case. This scratchpad does not run code.
Notes stay in this browser when storage is available.
Read the solution approach
Use a queue seeded with the root if present. At each step, remove exactly the number of nodes currently queued, collect their values, and enqueue their left then right children. Append the collected level and repeat. An empty tree yields an empty list.
Complexity
O(n) time and O(w) auxiliary space for maximum width w, excluding output.
Before moving on, explain why the algorithm is correct and trace a boundary case without looking at the approach.