v9.1.1
Menu

Chapter 6: Breadth First Search

Week 6

Master BFS traversal and its applications on binary trees. Learn how queue-based level-by-level exploration solves problems where DFS falls short, including level-order traversal, zigzag ordering, right side view, and finding minimum depth efficiently.

Topics
5
Demos
5
Min read
25

Chapter Overview

Breadth First Search (BFS) explores a tree level by level, visiting all nodes at depth d before any node at depth d+1. While DFS dives deep into one branch before backtracking, BFS spreads wide across each level using a queue to maintain the frontier of nodes to visit next.

This level-by-level property makes BFS the natural choice for problems that involve layers, levels, or finding the shortest path. When you need to process nodes in order of their distance from the root, BFS gives you that guarantee for free.

The core BFS pattern is simple: start with the root in a queue, then repeatedly dequeue a node, process it, and enqueue its children. The variation that makes BFS truly powerful for tree problems is level-aware BFS, where you process one full level per iteration by tracking the queue size at each step.

This chapter covers:

  • BFS Fundamentals: The queue-based traversal pattern and when to choose BFS over DFS
  • Level-Order Traversal: Collecting all nodes grouped by their level
  • Zigzag Level Order: Alternating the direction of traversal at each level
  • Right Side View: Identifying the last visible node at each level
  • Minimum Depth: Using BFS to find the shortest root-to-leaf path

Chapter Roadmap

Click any topic to jump in

Interactive demo
1
BFS Fundamentals

Queue-based level-by-level traversal — the FIFO pattern that visits nearby nodes before distant ones.

Queue-Based TraversalWhen BFS Beats DFS
The canonical level grouping
2
Level-Order Traversal

Group tree nodes by depth using queue-size snapshots — the canonical BFS application on binary trees.

Level Grouping with Queue SizeBottom-Up Level Order
Per-level variations

Direction, rightmost, and more

3
Zigzag Level Order

Alternate traversal direction per level — same BFS with a per-level reverse or a deque twist.

Alternating Direction with a FlagDeque-Based Insertion Alternative
4
Right Side View

Capture the last node at each level — a one-line tweak that reveals the rightmost visible profile.

Last Node Per LevelDFS Alternative for Right Side View
Shortest-path guarantees
5
Minimum Depth

First-leaf-wins shortest path — why BFS beats DFS when the answer is close to the root.

BFS for Shortest Path in TreesDFS Pitfall: Nodes with One Child

Topics

5 topics in this chapter

A social network wants to suggest friends of friends before friends of friends of friends, and a game wants the enemy nearest to the player, not merely some enemy. In both cases, the order of the search matters: closer items must be examined before farther ones. The depth-first search of earlier chapters does the opposite, diving down one branch to the bottom before looking at a sibling that may be right next to the start.

The previous chapter, Backtracking, used DFS to enumerate every path through a state-space tree. Breadth-first search (BFS) visits nodes in order of distance from the start: first the root, then all nodes one edge away, then all nodes two edges away. The mechanism is a first-in, first-out queue. Removing a node from the front and appending its children to the back guarantees that everything at depth d is processed before anything at depth d + 1.

We first implement queue-based traversal on a binary tree and trace the queue step by step. Then we compare BFS with DFS, when each finds an answer sooner, and what each costs in memory, width versus height.

Definition

Breadth-first search traverses a tree or graph in order of distance from a start node. It keeps a FIFO queue, initialized with the start node, and repeatedly removes the front node, processes it, and appends its unvisited neighbours to the back. On a tree it visits every node once in O(n) time, using O(w) memory, where w is the maximum width of any level.

In this topic

  1. 1Queue-Based Traversal
  2. 2When BFS Beats DFS
1 of 2
Queue-Based Traversal

BFS relies on a queue (first-in, first-out) to track which nodes to visit next. You initialize the queue with the root, then loop: dequeue one node, process it, and enqueue its left and right children (if they exist). Because the queue preserves insertion order, nodes enqueued first (closer to the root) are processed before nodes enqueued later (deeper in the tree). This produces a level-by-level traversal without any explicit depth tracking. In Python, use collections.deque for O(1) popleft operations instead of a list, which would be O(n) for pop(0).

Mathematical Intuition

BFS maintains a FIFO queue QQ representing the frontier of nodes to visit. Starting from the root, it repeatedly dequeues a node uu and enqueues its children, guaranteeing that any node at depth dd is dequeued before any node at depth d+1d+1. This is the invariant that makes BFS level-ordered. The time complexity is O(n)O(n) because each of the nn nodes is enqueued and dequeued exactly once, and each operation is O(1)O(1) with collections.deque (using a list would give O(n)O(n) per pop(0), pushing the total to O(n2)O(n^2)). Space is O(w)O(w) where ww is the maximum width of the tree — up to n/2n/2 for a complete binary tree.

Example:

Implement basic BFS on a binary tree and print nodes in level order.

2 of 2
When BFS Beats DFS

BFS is the better choice when the answer lies close to the root or when you need to process nodes by their level. For minimum depth problems, BFS finds the first leaf encountered and immediately returns --- DFS would need to explore the entire tree to be sure it found the shallowest leaf. For level grouping problems, BFS naturally groups nodes by level, while DFS requires passing a depth parameter and managing a separate data structure. BFS also guarantees shortest path in unweighted graphs. However, BFS uses O(w) space where w is the maximum width of the tree, which can be up to n/2 for a complete tree. DFS uses O(h) space for the recursion stack, where h is the height.

Mathematical Intuition

BFS is optimal when the answer lies at shallow depth dd because it explores only O(bd)O(b^d) nodes (where bb is branching factor) before finding it, while DFS may explore an entire subtree of depth hh. For minimum-depth problems, BFS terminates at the first leaf with worst-case cost O(bdmin⁡)O(b^{d_{\min}}), while DFS incurs O(n)O(n) in the worst case. The trade-off is space: BFS uses O(bd)O(b^d) memory for the frontier while DFS uses only O(h)O(h) recursion stack. For wide shallow trees, BFS dominates; for narrow deep trees, DFS wins on memory.

Example:

Compare BFS and DFS approaches for finding whether a value exists near the root of a wide, shallow tree.