Skip to content
Tree & GraphIntermediate

DFS (Pre/In/Post-Order)

Explore as deep as possible along each branch before backtracking. Use pre-order, in-order, or post-order depending on when you process the node.

Problem: Maximum Depth of Binary Tree

Find the maximum depth (height) of the binary tree using DFS.

3
9
20
15
7
DefaultVisitingVisited

Visit root node 3

Start DFS at root. Depth = 1. Recursively explore left and right subtrees.

Current Depth
1
Max Depth
1
Step 1/8
Speed:

When to Use

  • Tree traversal (any order)
  • Path-related problems
  • Explore all possibilities
  • Connected components

Key Indicators

  • Tree/graph path
  • Depth-related
  • All paths
  • Connected components

Complexity

Time

O(V + E)

Space

O(h) tree / O(V) graph

Common Problems

Maximum Depth of Binary TreePath SumNumber of IslandsClone GraphValidate BST

Code

def dfs(node):
    if not node: return
    # pre-order: process here
    dfs(node.left)
    # in-order: process here
    dfs(node.right)
    # post-order: process here

Want all 29 patterns with detailed visual walkthroughs?

The complete book includes 84 practice problems, full decision tree, and illustrated step-by-step solutions.

Book Coming Soon ($4.99)