Depth-First Search Tree Visualization

How Depth-First Search Works on Trees

Depth-First Search (DFS) on a tree starts at the root and explores as far as possible along each branch before backtracking. In this visualization, we're using an in-order traversal: left subtree, root, right subtree. The algorithm visits the left child, then the node itself, and finally the right child before backtracking.

Color representation:

  • Blue nodes are unvisited
  • Yellow node is the current node being explored
  • Green nodes have been visited

function dfs(graph, start):
    visited = set()
    stack = [start]
    while stack is not empty:
        vertex = stack.pop()
        if vertex not in visited:
            visit(vertex)
            visited.add(vertex)
            for neighbor in graph[vertex]:
                if neighbor not in visited:
                    stack.push(neighbor)
        visualize(graph, visited, stack)