Tree Breadth-First Search
Visit a tree level by level using a queue.
python, tree, breadth first, queue, traversalVisit 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
- QueueACurrent focus
- 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.
