Tree Breadth-First Search
Process a tree level by level with a queue — level order, zigzag, right side view, minimum depth and connecting levels.
Tree BFS visits nodes level by level using a queue. The key trick: at the start of each level, record the queue's size — exactly that many nodes belong to the current level.
Level order: [3], [9, 20], [15, 7]
When to use this pattern
- Anything per level: level averages, largest value per row, zigzag order.
- The minimum depth or the shallowest node satisfying a condition (BFS finds it first).
- Left/right side view, connecting nodes on the same level.
- Serialising a tree level by level.
The template
List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Deque<TreeNode> q = new ArrayDeque<>();
q.offer(root);
while (!q.isEmpty()) {
int size = q.size(); // nodes in this level
List<Integer> level = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
TreeNode n = q.poll();
level.add(n.val); // ← per-node work
if (n.left != null) q.offer(n.left);
if (n.right != null) q.offer(n.right);
}
res.add(level); // ← per-level work
}
return res;
}from collections import deque
def level_order(root):
res = []
q = deque([root] if root else [])
while q:
level = []
for _ in range(len(q)): # nodes in this level
n = q.popleft()
level.append(n.val) # per-node work
if n.left: q.append(n.left)
if n.right: q.append(n.right)
res.append(level) # per-level work
return resfunction levelOrder(root: TreeNode | null): number[][] {
const res: number[][] = [];
let level = root ? [root] : [];
while (level.length) {
res.push(level.map((n) => n.val));
const next: TreeNode[] = [];
for (const n of level) {
if (n.left) next.push(n.left);
if (n.right) next.push(n.right);
}
level = next; // swap in the next level
}
return res;
}Change only the two marked lines to solve the variants:
| Problem | Per-level change |
|---|---|
| Level averages | Sum the level, divide by size |
| Largest value in each row | Track the max |
| Right side view | Record the last node of each level |
| Zigzag order | Reverse every other level (or insert at the front) |
| Bottom-up order | Reverse the final list |
| Minimum depth | Return the depth at the first leaf you meet |
| Connect next-right pointers | Link each node to the next one dequeued in the same level |
Right side view and minimum depth
List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
Deque<TreeNode> q = new ArrayDeque<>();
if (root != null) q.offer(root);
while (!q.isEmpty()) {
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode n = q.poll();
if (i == size - 1) res.add(n.val); // last in level
if (n.left != null) q.offer(n.left);
if (n.right != null) q.offer(n.right);
}
}
return res;
}
int minDepth(TreeNode root) {
if (root == null) return 0;
Deque<TreeNode> q = new ArrayDeque<>(List.of(root));
for (int depth = 1; ; depth++) {
for (int i = q.size(); i > 0; i--) {
TreeNode n = q.poll();
if (n.left == null && n.right == null) return depth; // first leaf
if (n.left != null) q.offer(n.left);
if (n.right != null) q.offer(n.right);
}
}
}def right_side_view(root):
res, q = [], deque([root] if root else [])
while q:
size = len(q)
for i in range(size):
n = q.popleft()
if i == size - 1:
res.append(n.val)
if n.left: q.append(n.left)
if n.right: q.append(n.right)
return res
def min_depth(root):
if not root:
return 0
q, depth = deque([root]), 1
while q:
for _ in range(len(q)):
n = q.popleft()
if not n.left and not n.right:
return depth
if n.left: q.append(n.left)
if n.right: q.append(n.right)
depth += 1function rightSideView(root: TreeNode | null): number[] {
const res: number[] = [];
let level = root ? [root] : [];
while (level.length) {
res.push(level[level.length - 1].val);
level = level.flatMap((n) => [n.left, n.right].filter((x): x is TreeNode => !!x));
}
return res;
}Practice problems
- Binary Tree Level Order Traversalmedium
- Average of Levels in Binary Treeeasy
- Minimum Depth of Binary Treeeasy
- Binary Tree Zigzag Level Order Traversalmedium
- Binary Tree Right Side Viewmedium
- Find Largest Value in Each Tree Rowmedium
- Populating Next Right Pointers in Each Nodemedium
- Maximum Width of Binary Treetrack positional indicesmedium
- Serialize and Deserialize Binary Treehard
Key takeaways
- Use a queue; snapshot its size to process exactly one level at a time.
- Most variants change only the per-node and per-level lines.
- BFS finds the shallowest target first: minimum depth, nearest leaf.
- Space is O(maximum width) — up to n/2 for a full tree.