Binary Tree Level Order Traversal
BFS a level at a time by draining the queue's current size.
Approach
Use a queue seeded with the root. At each level, record the current queue size, then dequeue exactly that many nodes (collecting their values and enqueueing their children). Each batch is one level's output.
Time complexity
O(n)
Space complexity
O(n)
Common mistake
Not snapshotting the queue length before the inner loop, which mixes nodes from two levels together.
See it run, step by step
Generate an interactive lesson for Binary Tree Level Order Traversal — trace every variable and watch the algorithm execute until it clicks.
Start a lesson on Binary Tree Level Order Traversal