Tree DFS
easy 18 minDepth-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
Tree DFS in 75 seconds
1:25Reel
How it works
Step through the idea, or press Play.
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
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)))One call of dfs(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
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
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
Side by side
All three orders on one tree
| Traversal | Order | When the node is processed | Tree 1 / 2, 3 / 4, 5, 6, 7 | Typical use |
|---|---|---|---|---|
| Preorder (NLR) | root, left, right | Before its children | 1, 2, 4, 5, 3, 6, 7 | Copy, serialize, prefix expression |
| Inorder (LNR) | left, root, right | Between its children | 4, 2, 5, 1, 6, 3, 7 | BST sorted order, validate BST |
| Postorder (LRN) | left, right, root | After its children | 4, 5, 2, 6, 7, 3, 1 | Delete tree, subtree values, postfix |
Which order do I need?
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.
- 1push dfs(1)stack: 1
- 2push dfs(2)stack: 1, 2
- 3push dfs(4)stack: 1, 2, 4
- 4pop 4, push 5stack: 1, 2, 5
- 5pop 5, pop 2stack: 1
- 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
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))The iterative inorder loop
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 nodes in its left subtree and in its right. A call does a constant amount of work plus its two recursive calls.
Time: each node is handled once
None, whatever the shape.Space: one root-to-leaf path
| Tree shape | Height h | DFS stack | BFS queue (for contrast) |
|---|---|---|---|
| Balanced | : the bottom level holds about | ||
| Skewed (a chain) | |||
| Any tree | , = widest level |
Patterns
Classic problems, three shapes
- 1
Return values up (max depth)
Base case returns 0 for
None; each node returns1 + max(left, right). Height, size, diameter and balanced-check work the same way. - 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.orstops at the first success. - 3
Change the tree (invert)
Swap
node.leftandnode.right, then recurse into both. Each node is touched once, .
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) # 3DFS or BFS
Choosing between DFS and BFS
Pick the traversal
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: against .
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 .
- 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.