Reading preferences
Concept

Tree Breadth-First Search

Visit a tree level by level using a queue.

python, tree, breadth first, queue, traversal

Visit in layers

Breadth-first search (BFS) visits a root, then its children, then their children. A queue removes the oldest waiting node and adds its children at the back.

Python illustration

from collections import deque

def breadth_first(root):
    if root is None:
        return []
    queue = deque([root])
    visited = []
    while queue:
        value, children = queue.popleft()
        visited.append(value)
        queue.extend(children)
    return visited

tree = ("A", [("B", [("D", [])]), ("C", [])])
print(breadth_first(tree))

Prepared output: ['A', 'B', 'C', 'D']. Each node is a value and an ordered list of children.

See the reasoning

Visit with a queue

Follow the first-in first-out frontier. This is a prepared demonstration, not live code execution.

Start

Queue and visit order
  1. QueueACurrent focus
  2. Visitednone

The root is the first waiting node.

Queue invariant and cost

The queue contains discovered but unvisited nodes in level order; appending children after waiting nodes preserves that order. For a finite tree with n nodes, time is O(n). The queue takes O(w) space for maximum width w; the returned list takes O(n). A general graph may contain cycles or shared nodes and needs an appropriate visited set.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What holds nodes waiting to be visited?
2. Which nodes are visited before the next level?
3. What does this function return for None?
4. What can dominate auxiliary space?

References and further reading