Iterative DFS
medium 22 minIterative DFS replaces the hidden call stack with an explicit one.
Video lesson · Chapter 1 of 9
Archive closeout
Iterative DFS in 75 seconds
1:19Reel
How it works
Step through the idea, or press Play.
Decide what a frame must remember. The node (or cell) plus enough state to know what to do when it comes back to the top: enter or exit, next neighbour, partial result
Understand it
Start here
Why make the stack explicit
Every recursive DFS already uses a stack: the call stack. Iterative DFS keeps the same last-in, first-out walk in an ordinary list that you own. Same visiting order, same or time. What changes is who holds the frames, and that brings three things recursion cannot give: no depth limit, the ability to pause, and full control over what each frame stores.
Recap: tree traversals
Iterative preorder, inorder and postorder with a stack, and the reverse trick, are taught step by step in Tree DFS. This page starts where that one stops.
Recap: the stack
Push and pop at the top in ; a Python list with
appendandpop. See Stack.Recap: call frames
How each call waits for the one above it is walked through in Recursion: factorial.
Recap: graphs and grids
Adjacency lists, visited sets and 4-direction neighbours: Intro to graphs and Matrix DFS.
Under the hood
What a recursive call really stores
Each call pushes a stack frame: its arguments, its local variables and the return address (which line to resume at when the inner call returns). Frames live in a fixed-size region of memory, and the interpreter may also impose its own counter. For DFS the depth is the length of the current path, so the memory is:
Call-stack memory
Typical recursion ceilings (defaults, they vary by platform)
| Language | What limits depth | Rough depth before failure | Error |
|---|---|---|---|
| Python (CPython) | sys.getrecursionlimit(), default 1000 | about 1,000 calls | RecursionError |
| Java | thread stack size (-Xss), often 512 KB to 1 MB | about 10,000 to 20,000 simple calls | StackOverflowError |
| JavaScript (V8) | engine stack size | about 10,000 calls | RangeError |
| C / C++ | OS thread stack, often 8 MB on Linux, 1 MB on Windows | depends on frame size | segmentation fault |
The decision
When to avoid recursion
Recursion or an explicit stack?
Make it iterative when
- Input depth is unbounded: skewed trees, chains of 10^5 nodes, 1000 × 1000 grids.
- You need an iterator or generator that hands out one node at a time (a BST iterator).
- You need to stop early and resume later, or run many walks side by side.
- The platform has a small stack: embedded systems, worker threads, browsers.
Recursion is fine when
- Depth is small and known: a balanced BST has about 20 levels for a million keys.
- Readability matters most and the input is bounded (most interview trees).
- Backtracking with clean undo where depth equals the number of choices, like N-Queens.
- You will start recursive in the interview, then convert if asked.
Recursive vs iterative at a glance
| Aspect | Recursive | Iterative |
|---|---|---|
| Code length | shorter | longer |
| Stack overflow risk | yes, past the depth limit | no, only memory |
| Control (pause, resume, custom frames) | less | more |
| Time and space | , | , (same) |
| In interviews | usually accepted first | strong follow-up answer |
Already covered
Recap: the three stack traversals
Tree 1 / 2, 3 / 4, 5, 6, 7 with an explicit stack
| Order | Result | Stack rule (PIP) |
|---|---|---|
| Preorder | 1, 2, 4, 5, 3, 6, 7 | pop and visit, then push right before left so left pops first |
| Inorder | 4, 2, 5, 1, 6, 3, 7 | go left till None pushing, pop and visit, then go right |
| Postorder | 4, 5, 2, 6, 7, 3, 1 | push left before right (gives root, right, left), then reverse |
Technique 1
Simulating the call stack with (node, state) frames
Any recursion can be converted mechanically. A real frame holds the arguments and a resume point. So store (node, state) in each stack entry, where state says which part of the function runs next. For DFS two states are enough: enter (first visit, schedule the children) and exit (children done, do the after-work). Return values go on a second stack or into a dictionary.
The enter / exit loop
class Node: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef evaluate(root): stack, vals = [(root, False)], [] while stack: node, seen = stack.pop() if node.left is None: # leaf: a number vals.append(node.val) elif not seen: # enter: schedule stack.append((node, True)) stack.append((node.right, False)) stack.append((node.left, False)) else: # exit: combine b, a = vals.pop(), vals.pop() vals.append(a + b if node.val == "+" else a * b) return vals[0]expr = Node("*", Node("+", Node(2), Node(3)), Node(4))print(evaluate(expr)) # 20Technique 2
Postorder with one stack and a prev pointer
Keep the current root-to-node path on the stack and remember prev, the last node you output. When the node on top has a right child, there are only two possibilities: you have not gone right yet, or you just came back from there. If top.right is prev, the right subtree is finished, so the node is ready to output.
One-stack postorder
class TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef postorder(root): out, stack = [], [] curr, prev = root, None while curr or stack: while curr: stack.append(curr) curr = curr.left top = stack[-1] if top.right and top.right is not prev: curr = top.right else: out.append(top.val) prev = stack.pop() return outt = TreeNode(8, TreeNode(3, TreeNode(1), TreeNode(6)), TreeNode(10, None, TreeNode(14)))print(postorder(t)) # [1, 6, 3, 14, 10, 8]Technique 3
Morris inorder: O(1) extra space
The stack in inorder exists only to climb back to an ancestor. Morris finds a spare pointer for that job: the inorder predecessor of curr (rightmost node of its left subtree) always has right = None. Point it at curr (a thread), go left, and when the walk later follows the thread back, remove it and visit curr.
One Morris step
Why it is still linear
class TreeNode: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, rightdef morris_inorder(root): out, curr = [], root while curr: if curr.left is None: out.append(curr.val) curr = curr.right else: pred = curr.left while pred.right and pred.right is not curr: pred = pred.right if pred.right is None: pred.right = curr # thread curr = curr.left else: pred.right = None # unthread out.append(curr.val) curr = curr.right return outt = TreeNode(4, TreeNode(2, TreeNode(1), TreeNode(3)), TreeNode(5))print(morris_inorder(t)) # [1, 2, 3, 4, 5]print(morris_inorder(t)) # same again: the threads were removedTechnique 4
Iterative DFS on graphs: mark on pop or on push
Graphs have cycles, so a node can be reached along many edges and you need a seen set. When you add to it changes the result. On the graph A-B, A-C, B-C, B-E, C-D (neighbours in alphabetical order), recursion visits A, B, C, D, E.
| Mark on pop | Mark on push | |
|---|---|---|
When a node joins seen | when it is popped and processed | when it is first pushed |
| Duplicates on the stack | yes, skip them with continue | never |
| Order on the example | A, B, C, D, E (same as recursion) | A, B, E, C, D (different) |
| Peak stack size | ||
| Use for | true DFS order, DFS tree, discovery and finish times | reachability, components, flood fill |
Choosing where to mark
adj = {"A": ["B", "C"], "B": ["A", "C", "E"], "C": ["A", "B", "D"], "D": ["C"], "E": ["B"]}def dfs_on_pop(start): seen, order, stack = set(), [], [start] while stack: u = stack.pop() if u in seen: continue seen.add(u) order.append(u) for v in reversed(adj[u]): if v not in seen: stack.append(v) return orderdef dfs_on_push(start): seen, order, stack = {start}, [], [start] while stack: u = stack.pop() order.append(u) for v in reversed(adj[u]): if v not in seen: seen.add(v) stack.append(v) return orderprint(dfs_on_pop("A")) # ['A', 'B', 'C', 'D', 'E']print(dfs_on_push("A")) # ['A', 'B', 'E', 'C', 'D']Technique 5
Flood fill and backtracking on a grid
A grid is a graph whose neighbours are the four adjacent cells (Matrix DFS covers the recursive version). A region can be as large as the whole grid, so on a 1000 × 1000 image a recursive fill may need a million nested calls. With an explicit stack and mark on push, each cell enters the stack at most once.
def flood_fill(grid, sr, sc, new): old = grid[sr][sc] if old == new: return grid # nothing to do, and avoids looping R, C = len(grid), len(grid[0]) grid[sr][sc] = new stack = [(sr, sc)] while stack: r, c = stack.pop() for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == old: grid[nr][nc] = new stack.append((nr, nc)) return gridg = [[1, 1, 0], [0, 1, 0], [1, 0, 1]]print(flood_fill(g, 0, 0, 2)) # [[2, 2, 0], [0, 2, 0], [1, 0, 1]]big = [[1] * 5000] # one long row: recursion would failprint(flood_fill(big, 0, 0, 7)[0][-1]) # 7Backtracking needs one more idea: when a path is abandoned, its choices must be undone. That is the exit frame again. Push (cell, False) to enter (mark it on the path), push (cell, True) under the neighbours, and when the exit frame pops, unmark the cell. This finds whether a word exists in a letter grid, or all paths through a maze, without recursion.
def exists(board, word): R, C = len(board), len(board[0]) for sr in range(R): for sc in range(C): if board[sr][sc] != word[0]: continue on_path = set() stack = [(sr, sc, 0, False)] while stack: r, c, i, leaving = stack.pop() if leaving: on_path.discard((r, c)) # undo the choice continue if i == len(word) - 1: return True on_path.add((r, c)) stack.append((r, c, i, True)) # undo after the subtree for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)): nr, nc = r + dr, c + dc if (0 <= nr < R and 0 <= nc < C and (nr, nc) not in on_path and board[nr][nc] == word[i + 1]): stack.append((nr, nc, i + 1, False)) return Falseboard = ["ABCE", "SFCS", "ADEE"]print(exists(board, "ABCCED"), exists(board, "SEE"), exists(board, "ABCB")) # True True FalseTechnique 6
Cycle detection with three colours
In a directed graph, reaching an already-seen node is not enough to prove a cycle: it may be a node finished on another branch. You need to know whether it is still on the current path. Three colours say exactly that, and the iterative version gets the timing right with the same exit frame as technique 1.
A node's colour over time
def has_cycle(adj): WHITE, GRAY, BLACK = 0, 1, 2 color = {u: WHITE for u in adj} for s in adj: if color[s] != WHITE: continue stack = [(s, False)] while stack: u, leaving = stack.pop() if leaving: color[u] = BLACK continue if color[u] != WHITE: continue color[u] = GRAY stack.append((u, True)) for v in reversed(adj[u]): if color[v] == GRAY: return True if color[v] == WHITE: stack.append((v, False)) return Falseg = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": [], "E": ["A"]}print(has_cycle(g)) # Trueg["E"] = []print(has_cycle(g)) # False: C -> D alone is not a cycleComplexity
Same Big O, different limits
| Technique | Time | Extra space | Notes |
|---|---|---|---|
| (node, state) frames | two frames per internal node | ||
| One-stack postorder | no reversal list | ||
| Morris inorder | modifies pointers temporarily | ||
| Graph DFS, mark on pop | stack may hold duplicates | ||
| Graph DFS, mark on push | order can differ from recursion | ||
| Grid flood fill | each cell pushed at most once | ||
| Three-colour cycle check | exit frame turns GRAY to BLACK |
Why mark on pop can hold O(E) entries
Recap
Key takeaways
Key points
- Iterative DFS is recursion with the call stack moved into a list: same order, same Big O, no depth limit.
- Python's default limit is about 1,000 frames; raising it does not grow the C stack, so convert deep recursion to a loop.
- Any recursion converts with (node, state) frames: push an exit frame under the children to run code after them.
- One-stack postorder: if top.right is prev you are returning from the right, so output and pop.
- Morris inorder threads predecessors back to ancestors for O(1) extra space, then removes every thread.
- Graphs: mark on pop for the exact recursive order (skip stale duplicates), mark on push for no duplicates and an O(V) stack.
- Grids: mark on push, four directions, bounds first. Backtracking undoes choices in the exit frame.
- Directed cycles need three colours: an edge to GRAY is a back edge; an edge to BLACK is safe.