Iterative DFS
medium 22 minIterative DFS replaces the hidden call stack with an explicit one.
See it run
Replace the hidden call stack with one you control: frames with a state flag, a prev pointer, threads instead of a stack, and visited marks and colours for graphs and grids.
Operations
Call stack as (node, state) frames
Evaluate the expression tree (2 + 3) * 4 without recursion. Each frame remembers whether its children are done, and a value stack plays the part of return values.
Step 1 of 8
What recursion keeps for you
- eval(*) waiting on left
- eval(+) waiting on left
- eval(2) runningTOP
Recursively, eval(*) calls eval(+), which calls eval(2). Each call is a frame on the call stack holding its node, its locals and where to resume. At this moment three frames are waiting. To go iterative we must store that same information ourselves.
Step 1: What recursion keeps for you
def evaluate(root): stack = [(root, False)] # (node, children_done) vals = [] # return values of finished calls while stack: node, seen = stack.pop() if node.left is None: # leaf: a number vals.append(node.val) elif not seen: # first visit: schedule the work stack.append((node, True)) # come back after the children stack.append((node.right, False)) stack.append((node.left, False)) else: # second visit: children are done b, a = vals.pop(), vals.pop() vals.append(a + b if node.val == "+" else a * b) return vals[0]- Time
- O(n)
- Space
- O(h)
- Frames per node
- 2 (enter, exit)
- Recursion limit
- none
Any recursion converts this way: a frame holds the arguments plus a state saying which line to resume at, and a second stack (or a field in the frame) holds return values.
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Pushing children in the wrong order
majorA stack reverses what you push. Pushing left then right explores the right subtree first, so preorder or graph order no longer matches recursion.
Wrongstack.append(node.left)stack.append(node.right) # right pops firstRightstack.append(node.right)stack.append(node.left) # left pops first, like recursionMarking visited on push but expecting recursive order
majorMark on push claims a node for whoever pushes it first, so the visiting order and DFS tree differ from recursion. Algorithms that need discovery order (low-link, topological order by finish time) then give wrong answers.
Wrongfor v in reversed(adj[u]): if v not in seen: seen.add(v) # claimed early stack.append(v)Rightu = stack.pop()if u in seen: continueseen.add(u) # mark when actually visitedfor v in reversed(adj[u]): if v not in seen: stack.append(v)Not skipping stale entries when marking on pop
criticalWith mark on pop the same node can be on the stack several times. Without the check it is processed again, recorded twice, and on dense graphs the work explodes.
Wrongu = stack.pop()seen.add(u)order.append(u)Rightu = stack.pop()if u in seen: continueseen.add(u)order.append(u)One-stack postorder comparing values instead of nodes
majorprev must identify the node you just finished. Two nodes can hold the same value, so top.right.val == prev.val can fire on the wrong node and skip a whole subtree.
Wrongif top.right and top.right.val != prev_val: curr = top.rightRightif top.right and top.right is not prev: curr = top.rightLeaving Morris threads behind
criticalEach thread is removed only on the second arrival. If you return early (say, after finding the k-th node), some right pointers still point upward and the tree now contains cycles.
Wrongif count == k: return curr.val # threads above are still in placeRightif count == k and ans is None: ans = curr.val # keep walking so every thread is removed...return ansUsing one visited set for directed cycles
criticalReaching a finished node (a cross edge) looks the same as reaching a node on the current path. Only an edge to a GRAY node is a cycle; you need the exit frame to turn nodes BLACK.
Wrongif v in visited: return True # false alarm on C -> DRightif color[v] == GRAY: return True # back edge onlyif color[v] == WHITE: stack.append((v, False))
Interview tips
How to explain it
- Recursion uses the call stack; iterative DFS uses a list as the stack. Same order, same O(n) or O(V + E) time.
- The reason to switch: depth. Python stops at about 1,000 frames by default, and a skewed tree or a long grid path can be far deeper.
- To convert any recursion, store (arguments, resume state) in each frame and keep return values on a second stack.
Clarify before coding
- How deep can the input be? A chain of 10^5 nodes rules out plain recursion in Python.
- Do I need the exact recursive order, or only to reach every node?
- Directed or undirected? Directed cycle checks need three colours, undirected ones need a parent check.
- May I modify the tree temporarily (Morris), or must it stay read-only?
Templates to know cold
- Frames: stack = [(node, False)]; on False push (node, True) then children; on True do the after-children work.
- One-stack postorder: walk left pushing; if top.right and top.right is not prev go right, else output and prev = pop.
- Graph: pop, skip if seen, mark, push unseen neighbours reversed.
- Grid: mark on push, four directions, bounds check first.
Facts to have ready
- Iterative DFS has the same Big O as recursive; it removes the depth limit, not work.
- Mark on pop can hold O(E) stack entries; mark on push holds at most O(V).
- Morris inorder: O(n) time, O(1) extra space, temporarily modifies right pointers.
- sys.setrecursionlimit raises Python's counter but not the C stack; very deep recursion can still crash the interpreter.