AlgoViz

Tree DFS

easy 18 min

Depth-first search walks a tree by going as deep as possible down one branch before backing up to try the next.

See it run

Follow one branch all the way down before backing up, and see how the moment you record a node gives preorder, inorder or postorder.

Operations

Preorder (root, left, right)

Record each node the moment you arrive, before either child. On the tree 1 / 2, 3 / 4, 5 the output is 1, 2, 4, 5, 3: every parent appears before everything below it.

Step 1 of 9

Start: call dfs(1)

12453

out: [ ] · stack: 1

Preorder means root, then left, then right. We call dfs(1) on the root. Each call does three things in a fixed order: record the node, recurse left, recurse right. The current path of calls is the call stack.

Step 1: Start: call dfs(1)

def preorder(root):    out = []    def dfs(node):        if node is None:          # base case: an empty subtree            return        out.append(node.val)      # PRE: work before the children        dfs(node.left)        dfs(node.right)    dfs(root)    return out
Time
O(n)
Space
O(h) call stack
output
1, 2, 4, 5, 3
used for
copy, serialize, prefix expressions

PRE = process before the children. Use it when a parent must exist before its children: copying a tree, serializing it, printing a folder listing.

In the real world

The same tree dfs doing real jobs. Pick one and step through it.

A folder's size is the sum of everything inside it, so you can only total a folder after totalling its children. That is postorder, and it is how disk-usage tools walk a file system.

Step 1 of 4

How big is each folder?

/docscv2 MBnotes3 MBpicstrip5 MB

size(/) = ?

The root / holds docs and pics. docs holds cv (2 MB) and notes (3 MB); pics holds trip (5 MB). Files know their own size; folders do not.

Step 1: How big is each folder?

def folder_size(node):    if not node.children:                 # a file        return node.size    total = sum(folder_size(c) for c in node.children)   # children first    return total                          # then the folder: postorder

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • No base case for None

    critical

    Every call eventually reaches a missing child. Without if node is None: return, the next line reads None.val and raises AttributeError. Check for None first, before touching the node.

    Wrong
    def dfs(node):    out.append(node.val)      # crashes when node is None    dfs(node.left)    dfs(node.right)
    Right
    def dfs(node):    if node is None:          # base case first        return    out.append(node.val)    dfs(node.left)    dfs(node.right)
  • Pushing left before right in iterative preorder

    major

    A stack pops the last item pushed. Push left first and right pops first, so you get a mirrored order (1, 3, 2, 5, 4 instead of 1, 2, 4, 5, 3). Push the child you want next last.

    Wrong
    if node.left:    stack.append(node.left)if node.right:    stack.append(node.right)   # right pops first: wrong order
    Right
    if node.right:    stack.append(node.right)   # pushed first, popped laterif node.left:    stack.append(node.left)    # on top, popped next
  • Changing shared state without undoing it

    major

    When you collect paths in one shared list, appending a node on the way down but never popping it on the way back up leaves stale nodes in every later path. Undo the change after the recursive calls: that is backtracking.

    Wrong
    def dfs(node, path):    if node is None:        return    path.append(node.val)    if not node.left and not node.right:        paths.append(list(path))    dfs(node.left, path)    dfs(node.right, path)     # path keeps growing forever
    Right
    def dfs(node, path):    if node is None:        return    path.append(node.val)    if not node.left and not node.right:        paths.append(list(path))    dfs(node.left, path)    dfs(node.right, path)    path.pop()                # undo on the way back up
  • Running tree DFS on a graph without a visited set

    critical

    Trees have no cycles, so tree DFS never meets a node twice. Graphs do: an undirected edge alone makes 0 → 1 → 0 → 1 loop until RecursionError. Graph DFS must remember visited nodes.

    Wrong
    def dfs(node):    order.append(node)    for nxt in graph[node]:        dfs(nxt)              # loops forever on any cycle
    Right
    def dfs(node):    if node in visited:        return    visited.add(node)    order.append(node)    for nxt in graph[node]:        dfs(nxt)
  • Recursing on a very deep tree in Python

    minor

    Recursion depth equals tree height. A skewed tree of 10,000 nodes needs 10,000 frames, and Python stops at about 1,000 with RecursionError. Use the iterative version when the height can be large.

    Wrong
    preorder(chain_of_10000)   # RecursionError: maximum recursion depth exceeded
    Right
    preorder_iterative(chain_of_10000)   # explicit stack, no depth limit
  • Building lists by concatenation in every call

    minor

    return [root.val] + preorder(left) + preorder(right) copies lists at every level, so each value is copied once per ancestor: O(n·h) time, O(n²) on a skewed tree. Append to one shared list instead.

    Wrong
    def preorder(root):    if not root:        return []    return [root.val] + preorder(root.left) + preorder(root.right)
    Right
    def preorder(root):    out = []    def dfs(node):        if node:            out.append(node.val)            dfs(node.left)            dfs(node.right)    dfs(root)    return out

Interview tips

  • How to explain it

    • DFS goes as deep as possible along one branch, then backtracks. It uses a stack: the call stack when recursive, a list when iterative.
    • On a tree it visits each node once: O(n) time. The stack holds one root-to-leaf path: O(h) space, from O(log n) balanced to O(n) skewed.
    • Three orders, same walk: record the node before (pre), between (in) or after (post) its children.
  • Spot it in problems

    • The answer for a node comes from its children's answers (height, size, diameter, balanced): postorder, return values up.
    • A condition along a root-to-leaf path (path sum, max on path, valid range): preorder, pass state down.
    • Anything about sorted order in a BST (validate, k-th smallest): inorder.
  • Memory tricks

    • PRE = before, IN = in between, POST = after: the prefix tells you when the node is processed.
    • Post is the postcard you send after the trip: children first, parent last.
    • PIP for iterative: Preorder pushes right first, Inorder goes left till None, Postorder pushes left first and reverses.
  • Watch out

    • Check for None before using a node.
    • Graphs need a visited set; trees do not.
    • Undo shared state after the recursive calls when backtracking.
    • Deep or skewed trees can blow Python's recursion limit: go iterative.