Breadth-First Search Tree Visualization

How Breadth-First Search Works on Trees

Breadth-First Search (BFS) on a tree starts at the root and explores all nodes at the present depth before moving on to the nodes at the next depth level. It uses a queue to keep track of the child nodes that were encountered but not yet explored.

Color representation:

  • Blue nodes are unvisited
  • Light blue nodes are in the queue to be visited
  • Yellow node is the current node being explored
  • Green nodes have been visited

function bfs(graph, start):
    visited = set()
    queue = [start]
    while queue is not empty:
        vertex = queue.dequeue()
        if vertex not in visited:
            visit(vertex)
            visited.add(vertex)
            for neighbor in graph[vertex]:
                if neighbor not in visited:
                    queue.enqueue(neighbor)
        visualize(graph, visited, queue)