Level Order Traversal
Visit nodes level by level using BFS. Group each depth into its own result array.
Key concepts at a glance — for those who already know the basics.
Problem Statement
Binary Tree Level Order Traversal
Input: root = [1, null, 2, 3]
Output: [[1], [2], [3]]
Each depth becomes one array in result.
Input: root = [1, 2, 3, 4, 5, 6, 7]
Output: [[1], [2, 3], [4, 5, 6, 7]]
Classic BFS output grouped by level.
Constraints
- The number of nodes is in range [0, 100].
- Each node value is in range [-100, 100].
The Rule
Level by Level using Queue
Freeze current queue size, process exactly that many nodes, then move to the next level.
How to Think
Push root into queue
This starts BFS from top of tree.
Read level size before popping
That number defines the boundary of current level.
Collect values and enqueue children
Children naturally become the queue for next level.
Code
Complexity
Time
O(n)
Each node is processed once.
Space
O(w)
Queue can hold the widest level.
Interview Uses
Level based metrics
Count nodes per depth or compute level averages with the same BFS skeleton.
Zigzag traversal
Use level order and alternate insertion direction on every level.
Bottom up traversal
Collect level order then reverse once at the end.
Tree views
Left view and right view are level order with first or last pick per level.
Ready to see it in action?
Step through the visualizer to watch the algorithm state update live.