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.

Chapter mnemonic

Three tree traversal orders

Kids stay left to right. When does Dad get his photo?

If Dad is photographed between his two children, which traversal is that?

Inorder. Visit the left subtree, then the root, then the right subtree.

Video lesson · Chapter 1 of 6

A folder that cannot report yet

0:00 / 4:22

Tree DFS in 75 seconds

1:25Reel

How it works

Step through the idea, or press Play.

Step 1 of 3

Stop at None. An empty subtree returns straight away; every DFS function starts with this check

Understand it

Start here

What depth-first search is

Picture walking through a maze. You follow one corridor as far as it goes, hit a dead end, walk back to the last junction and try the next corridor. That is depth-first search (DFS): go deep first, go wide only when you have to.

On a binary tree that means: from a node, explore its entire left subtree, then its entire right subtree. Because both subtrees are themselves trees, the code is a short recursive function, and the computer's call stack remembers the way back for you.

  • Deep before wide

    Finish one branch completely before starting its sibling. The opposite of BFS, which goes level by level.

  • Backtracking

    When a branch ends at None, return to the parent and carry on with its next child.

  • A stack underneath

    The path of open calls is a stack: the most recent node is the one you return to first.

The template

One function, three places to do the work

Python
class TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, rightdef dfs(node):    if node is None:          # base case: an empty subtree        return    print("pre ", node.val)   # PRE: before the children    dfs(node.left)    print("in  ", node.val)   # IN: between the children    dfs(node.right)    print("post", node.val)   # POST: after the children#        1#      /   \#     2     3dfs(TreeNode(1, TreeNode(2), TreeNode(3)))
Every tree DFS is this skeleton. Where you put the work decides the order.
Edit and run it in your browser

One call of dfs(node)

Each node passes through three moments. Every traversal does the same walk; it only differs in which moment records the node.

Order 1

Preorder: root, left, right

Record the node the moment you arrive, then do its left subtree, then its right. On the tree with root 1, children 2 and 3, and 4, 5 under 2, the output is 1, 2, 4, 5, 3. A parent always appears before everything beneath it.

Preorder visit numbers

Go down the left edge recording as you go (1, 2, 4), back up to 2 for 5, back up to 1 for 3.
  • Copy a tree

    Create the parent first, then attach copies of its children.

  • Serialize

    Write the root, then the subtrees, with markers for None. The list can rebuild the exact tree.

  • Prefix expressions

    Preorder of an expression tree gives prefix notation: * + 2 3 4.

Order 2

Inorder: left, root, right

Finish the left subtree, then record the node, then do the right subtree. On a binary search tree, where everything left of a node is smaller and everything right is larger, this prints the values in sorted order. The BST with root 4, children 2 and 6, and leaves 1, 3, 5, 7 comes out as 1, 2, 3, 4, 5, 6, 7.

Why the output is sorted

inorder(v)=inorder(v.left)⏟all < v  ,  v  ,  inorder(v.right)⏟all > v\text{inorder}(v) = \underbrace{\text{inorder}(v.\text{left})}_{\text{all} \,<\, v} \;,\; v \;,\; \underbrace{\text{inorder}(v.\text{right})}_{\text{all} \,>\, v}
Every value smaller than vv is printed before it and every larger value after it, at every node. By induction on the height, the whole list is sorted.

Order 3

Postorder: left, right, root

Do both subtrees first and record the node last. On the five-node tree the output is 4, 5, 2, 3, 1: every child before its parent, the root at the very end. This is the order whenever a node needs its children's results.

  • Delete a tree

    Free the children before the parent, so no pointer is lost while it is still needed.

  • Subtree values

    Height, size, sums, folder sizes: combine the children's answers, then return yours.

  • Postfix expressions

    Postorder of an expression tree gives postfix: 2 3 + 4 *, which a stack evaluates directly.

Max depth is a postorder recurrence

depth(None)=0,depth(v)=1+max⁡(depth(v.left), depth(v.right))\text{depth}(\text{None}) = 0, \qquad \text{depth}(v) = 1 + \max\big(\text{depth}(v.\text{left}),\ \text{depth}(v.\text{right})\big)
The node can only answer after both children have answered, so the work sits after the two recursive calls.

Side by side

All three orders on one tree

TraversalOrderWhen the node is processedTree 1 / 2, 3 / 4, 5, 6, 7Typical use
Preorder (NLR)root, left, rightBefore its children1, 2, 4, 5, 3, 6, 7Copy, serialize, prefix expression
Inorder (LNR)left, root, rightBetween its children4, 2, 5, 1, 6, 3, 7BST sorted order, validate BST
Postorder (LRN)left, right, rootAfter its children4, 5, 2, 6, 7, 3, 1Delete tree, subtree values, postfix
In all three, the left subtree is finished before the right one starts. Only the position of the root changes.

Which order do I need?

Ask what information flows: up from the children (post), down from the parent (pre), or in sorted order (in).

Under the hood

DFS is a stack

When dfs(1) calls dfs(2), which calls dfs(4), each call waits on the call stack for the one above it to return. The most recently discovered node is the one finished first: last in, first out, exactly a stack. The stack always holds the path from the root to the current node.

Calls pushed and popped on the tree 1 / 2, 3 / 4, 5
  1. 1push dfs(1)stack: 1
  2. 2push dfs(2)stack: 1, 2
  3. 3push dfs(4)stack: 1, 2, 4
  4. 4pop 4, push 5stack: 1, 2, 5
  5. 5pop 5, pop 2stack: 1
  6. 6push dfs(3), pop allstack: empty

The deepest the stack ever gets is the height of the tree, here 3.

Without recursion

The iterative versions

Python
class TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, rightdef preorder(root):    stack, out = ([root] if root else []), []    while stack:        node = stack.pop()        out.append(node.val)        if node.right: stack.append(node.right)   # right first...        if node.left: stack.append(node.left)     # ...so left pops first    return outdef inorder(root):    stack, out, curr = [], [], root    while curr or stack:        while curr:                 # go left as far as possible            stack.append(curr)            curr = curr.left        curr = stack.pop()          # visit        out.append(curr.val)        curr = curr.right           # then the right subtree    return outdef postorder(root):    stack, out = ([root] if root else []), []    while stack:        node = stack.pop()        out.append(node.val)        # root, right, left        if node.left: stack.append(node.left)        if node.right: stack.append(node.right)    return out[::-1]                # reversed: left, right, roott = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3, TreeNode(6), TreeNode(7)))print(preorder(t), inorder(t), postorder(t))
All three orders with an explicit stack. Same O(n) time and O(h) stack as recursion, no depth limit.
Edit and run it in your browser

The iterative inorder loop

Go left till None, pop and record, go right, repeat. The stack holds nodes whose left side is not finished yet.

Iterative

  • No recursion limit: safe on deep or skewed trees.
  • Can pause and resume (generators, iterators).
  • More code, and postorder needs a trick.

Recursive

  • Shortest and clearest: start here in interviews.
  • Fails past about 1,000 levels in Python.
  • Hides the stack, which makes pausing hard.

Complexity

O(n) time, O(h) space

Let the root have kk nodes in its left subtree and n−k−1n - k - 1 in its right. A call does a constant amount of work cc plus its two recursive calls.

Time: each node is handled once

T(n)=T(k)+T(n−k−1)+c,T(0)=c⟹T(n)=(2n+1) c=O(n)T(n) = T(k) + T(n - k - 1) + c, \quad T(0) = c \quad\Longrightarrow\quad T(n) = (2n + 1)\,c = O(n)
Guess T(n)=(2n+1)cT(n) = (2n+1)c and substitute: (2k+1)c+(2(n−k−1)+1)c+c=(2n+1)c(2k+1)c + (2(n-k-1)+1)c + c = (2n+1)c. The 2n+12n + 1 counts nn real nodes plus n+1n + 1 calls on None, whatever the shape.

Space: one root-to-leaf path

S(n)=O(h),⌊log⁡2n⌋+1  ≤  h  ≤  nS(n) = O(h), \qquad \lfloor \log_2 n \rfloor + 1 \;\le\; h \;\le\; n
Only the calls on the current path are open at once. A balanced tree of n=106n = 10^6 nodes needs about 20 frames; a skewed one needs 10610^6.
Tree shapeHeight hDFS stackBFS queue (for contrast)
Balanced≈log⁡2n\approx \log_2 nO(log⁡n)O(\log n)O(n)O(n): the bottom level holds about n/2n/2
Skewed (a chain)nnO(n)O(n)O(1)O(1)
Any treehhO(h)O(h)O(w)O(w), ww = widest level
Time is O(n)O(n) for both. DFS is lighter on wide, bushy trees; BFS is lighter on long, thin ones.

Patterns

Classic problems, three shapes

  1. 1

    Return values up (max depth)

    Base case returns 0 for None; each node returns 1 + max(left, right). Height, size, diameter and balanced-check work the same way.

  2. 2

    Pass state down (path sum)

    Carry the remaining target into each call: has_path_sum(child, target - node.val). At a leaf, check whether it hit exactly 0. or stops at the first success.

  3. 3

    Change the tree (invert)

    Swap node.left and node.right, then recurse into both. Each node is touched once, O(n)O(n).

Python
class TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, rightdef max_depth(node):    if node is None:        return 0    return 1 + max(max_depth(node.left), max_depth(node.right))def has_path_sum(node, target):    if node is None:        return False    target -= node.val    if node.left is None and node.right is None:        return target == 0    return has_path_sum(node.left, target) or has_path_sum(node.right, target)def invert(node):    if node:        node.left, node.right = invert(node.right), invert(node.left)    return nodet = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)), TreeNode(3))print(max_depth(t), has_path_sum(t, 8), has_path_sum(t, 6))   # 3 True Falseprint(invert(t).left.val)                                      # 3
The three classics in a few lines each.
Edit and run it in your browser

DFS or BFS

Choosing between DFS and BFS

Pick the traversal

BFS finds the nearest answer first. DFS reaches the leaves first and keeps only one path in memory.

Use DFS when

  • You need any path, not the shortest.
  • The answer is a pre, in or post traversal.
  • Backtracking, cycle detection, topological sort.
  • Memory is tight and the tree is wide: O(h)O(h) against O(w)O(w).

Use BFS when

  • You need the shortest path in an unweighted graph.
  • The problem is about levels (level order, right side view).
  • Minimum moves or nodes at distance kk.
  • The answer is likely near the root.

Recap

Key takeaways

Key points

  • DFS goes as deep as possible down one branch before backtracking to try the next.
  • Every DFS starts with the base case: if the node is None, return.
  • Preorder = root, left, right; inorder = left, root, right; postorder = left, right, root.
  • Inorder of a BST is sorted. Postorder is for answers built from children. Preorder is for copying and passing state down.
  • DFS uses a stack: the call stack when recursive, a list when iterative.
  • Iterative preorder pushes right before left; iterative inorder goes left till None; iterative postorder reverses a mirrored preorder.
  • Time O(n), space O(h): O(log n) for a balanced tree, O(n) for a skewed one.
  • Graphs need a visited set; trees do not.

Sources