← Back to DSA Animator
Binary Tree Level Order Traversal LC #102 Medium BFS · Queue · Level Snapshot
Problem

Given the root of a binary tree, return the level order traversal of its nodes' values (i.e., from left to right, level by level).

Example 1
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]
Explanation: 3 levels: root=3, then 9 & 20, then 15 & 7.
Example 2
Input: root = [1]
Output: [[1]]
Constraints: 0 ≤ nodes ≤ 2000  |  −1000 ≤ Node.val ≤ 1000
Try Examples
Custom:
Approach
BFS with Level Snapshot using a Queue
Before each level, snapshot sz = queue.size(). Process exactly sz nodes — one full level — then enqueue their children. The snapshot prevents mixing parent & child levels.
Binary Tree
Level 1
Level 2
Level 3
Level 4+
In Queue
Processing
BFS Queue
Queue is empty
Output Levels
No levels collected yet…
Variables
Level #
sz (snapshot)
queue.size
0
result.size
0
Method Call Trace
Step Logic
Press ▶ Play or Next Step to begin the animation.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
If root == null return []; else offer root to queue
2
Snapshot sz = queue.size() — nodes at the current level
3
Poll exactly sz nodes: collect values, enqueue non-null children
4
Append completed level list to res; loop until queue empty
Time
O(n)
Space
O(n)
Why Level Snapshot Works

A plain BFS queue mixes nodes from different levels — you can't tell where one level ends. By capturing sz = queue.size() before the inner loop, we freeze the count of nodes at the current level. No matter how many children get enqueued during the inner loop, we always process exactly sz nodes — giving a clean, isolated layer. This is the key insight of iterative BFS level order.