DSA AnimatorDSA animations
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.

How to solve Binary Tree Level Order Traversal

LeetCode 102 · Medium · Tree · Pattern: BFS

Why the obvious approach is slow

A normal depth-first traversal goes branch by branch, not level by level. You could carry the depth along and group the values afterwards, but there's a more natural tool.

The key idea

Use a queue, which hands nodes back in the order they arrived. Before each level, read the queue's size: that is exactly how many nodes the level has. Pop that many nodes, record their values, and push their children for the next level.

Remember

Level by level means BFS with a queue. Read the queue size first, and that many nodes make one level.

Run the animation above on your own input, or watch the 1:47 video explanation of Binary Tree Level Order Traversal with a dry run and Java code.

More Tree problems