Reading preferences
Concept

Tree Depth-First Search

Follow a branch before returning to its siblings.

python, tree, depth first, stack, traversal

Follow a branch

Depth-first search (DFS) explores a branch before returning to another. This example visits each node before its children, called preorder. A stack keeps the pending branches.

Python illustration

def depth_first(root):
    if root is None:
        return []
    stack = [root]
    visited = []
    while stack:
        value, children = stack.pop()
        visited.append(value)
        stack.extend(reversed(children))
    return visited

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

Prepared output: ['A', 'B', 'D', 'C'].

See the reasoning

Visit with a stack

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

Start

Stack top is shown on the right
  1. StackACurrent focus
  2. Visitednone

The root is ready to pop.

Order and resource costs

Reversing children on insertion ensures the leftmost child is popped first. Each node is visited once in this finite tree. Time is O(n); the explicit stack can use O(n) space for a wide tree, and the returned list uses O(n). Recursive DFS instead uses the call stack and can hit Python's recursion limit on deep trees. Inorder and postorder are different visitation rules; graphs with cycles require a visited set.

Reflect on the concept

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

1. What does the stack store?
2. When is a node visited in this preorder example?
3. Why push children in reverse order?
4. What is needed for a graph with cycles?

References and further reading