Tree BFS (level-order traversal)
medium 16 minBreadth-first search visits a tree one level at a time, left to right, using a queue.
See it run
Watch the queue fill and drain as BFS visits a tree one level at a time, then reuse the same loop for right side view, zigzag and minimum depth.
Operations
Level order
Visit every node level by level, left to right, and group the values per level using the queue's length as a snapshot.
Step 1 of 12
The tree and an empty queue
Queue (front → rear)
empty
This level
empty
Result
empty
A perfect tree of seven nodes. BFS visits it like ripples in water: level 0, then level 1, then level 2. A queue (first in, first out) keeps the order for us.
Step 1: The tree and an empty queue
def 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 result- Time
- O(n)
- Space
- O(w)
- w on a perfect tree
- about n / 2 (last level)
- DFS stack instead
- O(h)
Read len(queue) once at the start of each pass. That number is the size of the current level; children added during the pass belong to the next one.
In the real world
The same tree bfs doing real jobs. Pick one and step through it.
Graphs can loop back on themselves. A visited set, filled when a node is enqueued, keeps BFS from going round forever or queuing a node twice.
Step 1 of 7
A graph with cycles
Queue (front → rear)
empty
Visited set
1 · 2 · 3 · 4 · 5 · 6
Visit order
empty
Six nodes and eight edges. 2-4-5 and 3-5-6 form loops, so a node can be reached from more than one side. A tree never needs this, but a graph does: track what you have seen.
Step 1: A graph with cycles
def graph_bfs(graph, start): visited = {start} queue = deque([start]) order = [] while queue: node = queue.popleft() order.append(node) for nb in graph[node]: if nb not in visited: visited.add(nb) # mark on enqueue queue.append(nb) return orderCommon mistakes
The bugs interviewers watch for, with the fix beside each.
Reading len(queue) inside the loop condition
criticalThe queue grows while you process a level, because children are appended. A while loop that re-reads the length, or a counter compared against a live length, runs into the next level and merges levels together. Snapshot the size once.
Wronglevel = []i = 0while i < len(queue): # length keeps growing node = queue.popleft() level.append(node.val) ...Rightlevel = []for _ in range(len(queue)): # evaluated once: this level only node = queue.popleft() level.append(node.val) ...Using list.pop(0) as the queue
criticallist.pop(0) shifts every remaining item, so each dequeue is O(n) and the whole traversal becomes O(n²) on a wide tree. collections.deque gives O(1) popleft.
Wrongqueue = [root]while queue: node = queue.pop(0) # O(n) shiftRightfrom collections import dequequeue = deque([root])while queue: node = queue.popleft() # O(1)Enqueuing None children
majorAppending node.left without checking puts None in the queue. The next popleft returns None and node.val crashes, or None values leak into the result.
Wrongqueue.append(node.left)queue.append(node.right)Rightif node.left: queue.append(node.left)if node.right: queue.append(node.right)Forgetting the empty-tree case
majordeque(None) is not empty, so the loop runs once and crashes on None.val. Return the empty answer first.
Wrongdef level_order(root): queue = deque([root]) # root may be None ...Rightdef level_order(root): if not root: return [] queue = deque([root]) ...Marking graph nodes visited when dequeued
majorOn a graph, a node can be discovered from several neighbours before it is dequeued. Marking late lets it enter the queue many times. Mark when enqueuing, and seed visited with the start.
Wrongwhile queue: node = queue.popleft() visited.add(node) # too late for nb in graph[node]: if nb not in visited: queue.append(nb)Rightvisited = {start}while queue: node = queue.popleft() for nb in graph[node]: if nb not in visited: visited.add(nb) # mark on enqueue queue.append(nb)Min depth that counts a missing child as a leaf
minorA recursive min(left, right) + 1 returns 1 for a root with only one child, because the missing side reports depth 0. A leaf needs both children missing. BFS with the leaf check avoids the trap and stops early.
Wrongdef min_depth(root): if not root: return 0 return 1 + min(min_depth(root.left), min_depth(root.right))Rightdef min_depth(root): if not root: return 0 queue = deque([(root, 1)]) while queue: node, d = queue.popleft() if not node.left and not node.right: return d ...
Interview tips
How to explain it
- BFS explores level by level, like ripples spreading in water. It uses a queue (FIFO), so nodes are processed in the order they were discovered.
- On a tree it visits each node once: O(n) time and O(w) space, where w is the widest level.
- For level grouping, read len(queue) at the start of each pass and dequeue exactly that many nodes.
- On a graph add a visited set; BFS then guarantees the shortest path in an unweighted graph, in O(V + E).
The template
- queue = deque([root]); while queue:
- size = len(queue); for _ in range(size): node = queue.popleft()
- Process node, then append node.left and node.right if they exist.
- After the inner loop, one level is complete: store it, flip a flag, or bump a depth counter.
Say these out loud
- Clarify first: can the root be None? Is it a binary tree or a graph? Can there be cycles?
- Mention the visited set straight away for graphs; it shows you understand cycles.
- Shortest path in an unweighted graph or the closest node: BFS is your answer.
- Know when not to use it: weighted edges need Dijkstra; tall thin trees use less memory with DFS.
Variants from one loop
- Right side view: keep the node at i == size - 1. Left side view: i == 0.
- Zigzag: appendleft on odd levels. Average of levels: sum / size per pass.
- Min depth: return at the first leaf. Max depth: count passes of the outer loop.
- Multi-source BFS: put every source in the queue before the loop starts.