AlgoViz

Tree BFS (level-order traversal)

medium 16 min

Breadth-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?

0:00 / 5:48

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.

Step 1 of 3

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 dd is visited before any node at depth d+1d + 1.

  • 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

BFS order is 1, 2, 3, 4, 5, 6, 7. Grouped by level it is [[1], [2, 3], [4, 5, 6, 7]].
One node's life in BFS
  1. 1DiscoveredParent is dequeued
  2. 2EnqueuedJoins at the rear
  3. 3WaitsIts level ahead drains
  4. 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. 1

    Initialise

    If the root is None, return. Otherwise create a queue holding the root.

  2. 2

    Dequeue

    Remove the front node with popleft(). This is the current node.

  3. 3

    Explore

    Look at its children (on a graph: all its neighbours).

  4. 4

    Enqueue

    Append each child that exists to the rear (on a graph: each unvisited neighbour, marking it visited).

  5. 5

    Repeat

    Go back to dequeue until the queue is empty.

Plain level-order traversal

Left before right keeps each level in left-to-right order.
Python
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]
BFS order of a seven-node tree, one flat list.
Edit and run it in your browser

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

The size is fixed before any child joins, so the inner loop never strays into the next level.
Python
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]]
Level-order traversal grouped by level.
Edit and run it in your browser

Complexity

O(n) time, O(w) space

Time: every node in and out once

T(n)=∑v∈tree(1⏟enqueue+1⏟dequeue+2⏟child checks)=4n=O(n)T(n) = \sum_{v \in \text{tree}} \big(\underbrace{1}_{\text{enqueue}} + \underbrace{1}_{\text{dequeue}} + \underbrace{2}_{\text{child checks}}\big) = 4n = O(n)
Each node is appended once and popped once, and checks at most two children. On a graph the child checks become edge checks, giving O(V+E)O(V + E).

Space: the widest level

S(n)=O(w),w=max⁡d∣leveld∣,perfect tree: w=2h=n+12S(n) = O(w), \qquad w = \max_{d} \lvert \text{level}_d \rvert, \qquad \text{perfect tree: } w = 2^{h} = \frac{n + 1}{2}
The queue holds at most one level plus part of the next. On a perfect tree of height hh with n=2h+1−1n = 2^{h+1} - 1 nodes, the last level has (n+1)/2(n + 1)/2 nodes, so the worst case is O(n)O(n).
Tree shapeWidth wwHeight hhBFS queueDFS stack
Perfect / completeabout n/2n/2log⁡2n\log_2 nO(n)O(n)O(log⁡n)O(\log n)
Skewed (a line)11nnO(1)O(1)O(n)O(n)
Star-like (wide, shallow)n−1n - 111O(n)O(n)O(1)O(1)
Random binary treevariesabout log⁡n\log nO(w)O(w)O(h)O(h)
Both traversals take O(n)O(n) time. Memory is the difference: BFS pays for width, DFS pays for height.

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

Swap the test for i == 0 and you get the left side view.
Python
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 gone
Tree [1, 2, 3, 4, 5, null, 6]: the view is [1, 3, 6].
Edit and run it in your browser

Pattern

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

Children always join the queue left then right. Only the output order flips.
Python
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]]
Zigzag on the seven-node tree.
Edit and run it in your browser

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

On tree [1, 2, 3, 4, null, null, 5] BFS returns 3 at node 4 and never processes node 5.
Python
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 leaf
Min depth with an early return.
Edit and run it in your browser

Beyond 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

dist(s)=0,dist(v)=dist(u)+1 where u discovered v,queue=[ d,…,d⏟front, d+1,…,d+1⏟rear ]\text{dist}(s) = 0, \qquad \text{dist}(v) = \text{dist}(u) + 1 \text{ where } u \text{ discovered } v, \qquad \text{queue} = [\,\underbrace{d, \dots, d}_{\text{front}},\ \underbrace{d+1, \dots, d+1}_{\text{rear}}\,]
Base case: the start has distance 0. A node is only added when discovered from a visited node, and FIFO keeps every distance-dd node ahead of every distance-(d+1)(d+1) node. If a shorter path to vv existed, vv would have been discovered earlier via that path, which is a contradiction.

Graph BFS with a visited set

BFS only reaches nodes connected to the start. For a disconnected graph, start a new BFS from every unvisited node.

Comparison

BFS versus DFS

FeatureBFSDFS
Data structureQueue (FIFO)Stack (LIFO) or recursion
Order on a treeLevel by levelPreorder, inorder, postorder
Shortest path, unweightedGuaranteedNot guaranteed
Space on a treeO(w)O(w), the widthO(h)O(h), the height
Space on a graphO(V)O(V)O(V)O(V)
Level-order outputNatural fitAwkward, needs a depth parameter
Best forNearby nodes, levels, fewest stepsDeep exploration, all paths, subtree answers
See tree DFS for the depth-first side, and binary tree for the structure both walk.

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

PatternKey techniqueExample problems
Level trackinglen(queue) at the start of each passLevel order, right side view, zigzag, average of levels
Shortest pathStore the distance with the nodeWord ladder, shortest bridge, open the lock
Multi-source BFSPut every source in the queue firstRotting oranges, walls and gates
Early terminationReturn as soon as the target is foundMin depth, path exists
State-space searchEach state is a nodeSliding puzzle, minimum moves
Bidirectional BFSSearch from both ends, meet in the middleWord 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 O(n)O(n): every node enters and leaves the queue once. Space is O(w)O(w), the widest level, up to about n/2n/2 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 O(V+E)O(V + E).
  • Use collections.deque; list.pop(0) makes BFS quadratic.

Sources