Tree Breadth-First Search

Process a tree level by level with a queue — level order, zigzag, right side view, minimum depth and connecting levels.

Beginner 2 min readLesson 11 of 25

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.

9157203
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;
}

Change only the two marked lines to solve the variants:

ProblemPer-level change
Level averagesSum the level, divide by size
Largest value in each rowTrack the max
Right side viewRecord the last node of each level
Zigzag orderReverse every other level (or insert at the front)
Bottom-up orderReverse the final list
Minimum depthReturn the depth at the first leaf you meet
Connect next-right pointersLink 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);
        }
    }
}
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.