Level-order traversal
Level-order traversal visits a tree one level at a time using a queue. Watch the queue fill with each level’s children.
Before you start: Pre-order, in-order, post-order, Queues: enqueue, dequeue; circular buffer.
The idea
Read this tree like a page: the top row first, then each row below, left to right. That order is 1, 2, 3, 4, 5, 6.
Pre-order, in-order and post-order all dive down one branch first. Many questions are about rows instead: the nodes at one depth, the last node of each row, the average of each row.
Intuition
A queue serves the oldest item first. 2 has just left, and its children 4 and 5 joined behind 3, so all of row 1 finishes before row 2.
A stack would serve 5 next and dive down. The queue's first-in, first-out rule is what keeps the rows in order.
Complexity
Time is O(n): every node joins the queue once and leaves it once. Space is O(w), where w is the widest level.
In a perfect tree the last level holds about half the nodes, so w can reach n / 2. That is O(n) space in the worst case.
With 15 nodes, all 8 leaves wait in the queue at once. A chain of 15 nodes would never hold more than 1.
Depth-first traversals pay for the height of the tree. Level order pays for its width. Pick the one whose cost is smaller for your tree shape.
Pitfalls
Read the queue length once, before the inner loop. The queue grows while the level runs, so a live length pulls level 2 into level 1.
In Python write size = len(queue) first and loop over range(size). In JavaScript, save queue.length in a variable before the loop starts.
Check each child before it joins the queue. A missing child is null, and reading null.val later crashes the program.
Also handle an empty tree at the top. Putting a null root in the queue fails on the first dequeue.
Variations
Change only what you do when a level ends. Keep its last node for a right side view, its average, or reverse odd levels for zigzag.
The loop stays the same in all three. The level size marks where each row ends, so the result for that row can be written then.
Level order is breadth-first search on a tree. A graph can reach one node by two paths, so graph BFS also keeps a seen set.
Code
Pseudocode
levelOrder(root)
if root = null: return []
queue ← [root]; out ← []
while queue is not empty
size ← length(queue); level ← []
repeat size times
node ← queue.dequeue(); level.append(node.val)
if node.left: queue.enqueue(node.left)
if node.right: queue.enqueue(node.right)
out.append(level)
return out
Python
from collections import deque
def level_order(root):
if root is None:
return []
queue, out = deque([root]), []
while queue:
size, level = len(queue), []
for _ in range(size):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
out.append(level)
return out
JavaScript
function levelOrder(root) {
if (root === null) return [];
const queue = [root], out = [];
let head = 0;
while (head < queue.length) {
const size = queue.length - head, level = [];
for (let k = 0; k < size; k++) {
const node = queue[head++];
level.push(node.val);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
out.push(level);
}
return out;
}
Java
List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> out = new ArrayList<>();
if (root == null) return out;
Deque<TreeNode> queue = new ArrayDeque<>(List.of(root));
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> level = new ArrayList<>();
for (int k = 0; k < size; k++) {
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
out.add(level);
}
return out;
}
Cost at a glance
| Time | O(n) |
|---|---|
| Space | O(w), w = widest level |
| Input | Binary tree |
| Output | Nodes level by level |
Practice problems (7)
Who leaves the queue next? Warm-up
Level order runs on this tree with a queue. Answer the prompts as the traversal runs: click the next node to be visited, then put all nodes in visit order.
Stack or queue? Warm-up
A traversal keeps waiting nodes in a container. It takes one node out, then puts that node's children in. Which container gives level order?
Complete the level loop Warm-up
Fill the three blanks so levelOrder returns the values of each level as its own list.
Level order Standard
Given the root of a binary tree, return its values level by level. Each level is a list of values from left to right, and the levels go from the root down.
Right side view Standard
You stand to the right of a binary tree and look at it. Return the values of the nodes you can see, from top to bottom. On each level you see only the rightmost node.
Average of levels Standard
Given the root of a binary tree, return the average value of the nodes on each level, from the root down. Answers within 0.00001 of the exact average are accepted.
Zigzag level order Challenge
Given the root of a binary tree, return its values level by level in zigzag order. Level 0 reads left to right, level 1 right to left, level 2 left to right again, and so on.
Related topics
Next on the path: Recursive problems on trees: height, size, mirror, paths