Tree BFS (level-order traversal)
medium 16 minBreadth-first search visits a tree one level at a time, left to right, using a queue.
Video lesson · Chapter 1 of 7
Who hears it first?
Tree breadth-first search — The first exit in Glow Cave
1:23Reel
Read caption
A glow gecko uses a FIFO queue to find the shallowest leaf of a cave-shaped tree, with every enqueue and dequeue visible. Join at the back, leave from the front. Near rooms get their turn first.
How it works
Step through the idea, or press Play.
Enqueue the root. The queue starts with one node; it holds the frontier of nodes discovered but not yet visited
Understand it
Start here
What tree BFS is
Breadth-first search (BFS) explores a tree level by level: the root, then all its children, then all its grandchildren. On a tree this is called level-order traversal. Picture dropping a stone in a still pond: the ripples reach everything at distance 1 first, then distance 2, and so on.
A queue drives it
A queue is first in, first out, so nodes are processed in exactly the order they were discovered.
Level N before N + 1
Every node at depth is visited before any node at depth .
Closest first
The first match BFS finds is the one nearest the root. That gives shortest paths and early exits.
The picture
Level order in one picture
A perfect tree read level by level
- 1DiscoveredParent is dequeued
- 2EnqueuedJoins at the rear
- 3WaitsIts level ahead drains
- 4DequeuedVisited, children join
Every node goes through these four stages exactly once, which is why the traversal is linear.
The algorithm
The queue loop
- 1
Initialise
If the root is
None, return. Otherwise create a queue holding the root. - 2
Dequeue
Remove the front node with
popleft(). This is the current node. - 3
Explore
Look at its children (on a graph: all its neighbours).
- 4
Enqueue
Append each child that exists to the rear (on a graph: each unvisited neighbour, marking it visited).
- 5
Repeat
Go back to dequeue until the queue is empty.
Plain level-order traversal
from collections import dequeclass TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightroot = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))def bfs_order(root): if not root: return [] order, queue = [], deque([root]) while queue: node = queue.popleft() # oldest discovery first order.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return orderprint(bfs_order(root)) # [1, 2, 3, 4, 5, 6, 7]The core trick
Level by level with the len(queue) snapshot
To group nodes by level, read len(queue) once at the top of each pass. At that moment the queue holds exactly one whole level and nothing else. Dequeue that many nodes; the children you append meanwhile are the next level, waiting behind.
One pass of the outer loop is one level
from collections import dequeclass TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef level_order(root): if not root: return [] result, queue = [], deque([root]) while queue: level = [] for _ in range(len(queue)): # snapshot: this level only node = queue.popleft() level.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(level) return resultroot = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))print(level_order(root)) # [[1], [2, 3], [4, 5, 6, 7]]Complexity
O(n) time, O(w) space
Time: every node in and out once
Space: the widest level
| Tree shape | Width | Height | BFS queue | DFS stack |
|---|---|---|---|---|
| Perfect / complete | about | |||
| Skewed (a line) | ||||
| Star-like (wide, shallow) | ||||
| Random binary tree | varies | about |
Pattern
Right side view
Looking at the tree from the right, you see one node per level: the rightmost. In level order that is the last node of each level, the one at index size - 1 in the inner loop.
Keep the last node of each level
from collections import dequeclass TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef right_side_view(root): if not root: return [] view, queue = [], deque([root]) while queue: size = len(queue) for i in range(size): node = queue.popleft() if i == size - 1: # last node of this level view.append(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right) return viewroot = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, None, TreeNode(6)))print(right_side_view(root)) # [1, 3, 6]root.right.right = Noneprint(right_side_view(root)) # [1, 3, 5]: 5 shows when 6 is gonePattern
Zigzag level order
Zigzag alternates direction: level 0 left to right, level 1 right to left, level 2 left to right. Keep the queue in its normal order and change only how each level is written: a deque for the level, append when going left to right and appendleft when going right to left.
Where each value goes
from collections import dequeclass TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef zigzag_level_order(root): if not root: return [] result, queue = [], deque([root]) left_to_right = True while queue: level = deque() for _ in range(len(queue)): node = queue.popleft() if left_to_right: level.append(node.val) # add at the back else: level.appendleft(node.val) # add at the front if node.left: queue.append(node.left) if node.right: queue.append(node.right) result.append(list(level)) left_to_right = not left_to_right return resultroot = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))print(zigzag_level_order(root)) # [[1], [3, 2], [4, 5, 6, 7]]Pattern
Minimum depth and the early exit
Minimum depth is the number of nodes on the shortest path from the root to a leaf (a node with no children). BFS reaches shallow nodes first, so the first leaf it dequeues is the shallowest one. Return right there; the rest of the tree is never touched.
Stop at the first leaf
from collections import dequeclass TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef min_depth(root): if not root: return 0 queue = deque([(root, 1)]) while queue: node, depth = queue.popleft() if not node.left and not node.right: return depth # first leaf = shallowest if node.left: queue.append((node.left, depth + 1)) if node.right: queue.append((node.right, depth + 1)) return 0root = TreeNode(1, TreeNode(2, TreeNode(4)), TreeNode(3, None, TreeNode(5)))print(min_depth(root)) # 3print(min_depth(TreeNode(1, TreeNode(2)))) # 2: the root has a child, so it is not a leafBeyond trees
Why BFS finds shortest paths
On a graph, BFS needs one addition: a visited set, because cycles can lead back to a node already seen. Mark a node when you enqueue it, not when you dequeue it, so it can enter the queue only once. With that, BFS gives the fewest edges from the start to every reachable node.
The proof by induction
Graph BFS with a visited set
Comparison
BFS versus DFS
| Feature | BFS | DFS |
|---|---|---|
| Data structure | Queue (FIFO) | Stack (LIFO) or recursion |
| Order on a tree | Level by level | Preorder, inorder, postorder |
| Shortest path, unweighted | Guaranteed | Not guaranteed |
| Space on a tree | , the width | , the height |
| Space on a graph | ||
| Level-order output | Natural fit | Awkward, needs a depth parameter |
| Best for | Nearby nodes, levels, fewest steps | Deep exploration, all paths, subtree answers |
Reach for BFS when
- The answer is per level: averages, maximums, the rightmost node.
- You need the closest node or the fewest steps.
- The target is probably near the root or start.
- Several sources spread at the same time.
Prefer DFS when
- The answer combines results from subtrees (height, diameter, path sums).
- You need every root-to-leaf path.
- The tree is very wide and shallow memory matters.
- You need a sorted walk of a BST (inorder).
Pattern spotting
The BFS patterns
| Pattern | Key technique | Example problems |
|---|---|---|
| Level tracking | len(queue) at the start of each pass | Level order, right side view, zigzag, average of levels |
| Shortest path | Store the distance with the node | Word ladder, shortest bridge, open the lock |
| Multi-source BFS | Put every source in the queue first | Rotting oranges, walls and gates |
| Early termination | Return as soon as the target is found | Min depth, path exists |
| State-space search | Each state is a node | Sliding puzzle, minimum moves |
| Bidirectional BFS | Search from both ends, meet in the middle | Word ladder on large dictionaries |
Is this a BFS problem?
Recap
Key takeaways
Key points
- Tree BFS visits nodes level by level, left to right, using a queue: dequeue from the front, enqueue children at the rear.
- Snapshot
len(queue)at the start of each pass to process exactly one level. That one line powers level order, right side view, zigzag and level averages. - Time is : every node enters and leaves the queue once. Space is , the widest level, up to about on a perfect tree.
- Min depth returns at the first leaf dequeued; BFS finds the closest answer first and can stop early.
- On graphs add a visited set and mark on enqueue. BFS then gives shortest paths in unweighted graphs in .
- Use
collections.deque;list.pop(0)makes BFS quadratic.