Lesson 27 of 40Advanced patterns
Recursion to Iteration
Replace the call stack with your own: iterative tree traversals, faithful graph DFS, BST iterators, and turning memoised recursion into tables.
A support ticket comes in: the comment export crashes for one customer. Their thread is a single reply chain 4,000 levels deep, and the export walks it with a tidy recursive function. Every other customer is fine because their threads are shallow. The function was correct; the call stack was simply not big enough. The fix is not a cleverer recursion but no recursion at all: the same walk, driven by a list you control.
You have now written recursive code for trees, graphs, backtracking and DP. This lesson is about that rewrite. You will learn why deep recursion fails in Python and JavaScript, how to turn any recursive traversal into a loop with an explicit stack, and the less obvious part: how to keep the exact order and the "return values" that recursion gave you for free. Interviewers ask for it directly ("now do it without recursion"), and it is the standard fix when a production walk over trees, graphs or nested data hits real-world depth.
Why deep recursion fails
Every call pushes a frame onto the call stack: the arguments, the local variables, and the place to resume when the call returns. The stack has a fixed budget.
- Python counts frames and stops at a limit, 1,000 by default (
sys.getrecursionlimit()). Past it you getRecursionError: maximum recursion depth exceeded. - JavaScript engines run out of actual stack memory. Node and Chrome typically fail somewhere around ten thousand frames, depending on how big each frame is, with
RangeError: Maximum call stack size exceeded. - Neither CPython nor V8 does tail-call optimisation. A call in tail position (
return f(n - 1)) still costs a frame. Safari's engine is the only major one that implements the ES2015 proper tail calls rule, so you cannot rely on it in Node. Do not tell an interviewer that tail recursion is safe in Python or JS.
Press Run (⌘ Enter) to see what happens.The loop handles a million steps without noticing. The recursive version dies as soon as depth passes the limit.
The hack, and why it is a hack
You will see this in competitive programming code:
import sys, threading
sys.setrecursionlimit(1 << 20)
threading.stack_size(1 << 27) # 128 MB stack for the new thread
threading.Thread(target=main).start()setrecursionlimit only raises a counter. If the real stack underneath runs out before the counter does, the process can crash hard instead of raising a clean exception. The thread trick gives a bigger real stack, but it depends on the platform, it does nothing in environments without real threads (like Pyodide in the browser), and it hides the problem rather than fixing it. In an interview, say you know the hack exists and then write the explicit stack. At work, a function whose memory use grows with input depth that you do not control should be iterative.
The core move: your list is the call stack
Recursion is a loop where the language keeps the to-do list for you. To remove it, keep the to-do list yourself:
- Decide what one frame needs to remember. Often just the node. Sometimes the node plus "how far through it am I".
- Push the starting frame onto a list.
- Loop: pop a frame, do its work, push the frames it would have called.
The one trap is order. A stack is last in, first out, so whatever you push last runs next. Pre-order (node, left, right) shows it best: push the right child first so the left child comes off first.
Press Run (⌘ Enter) to see what happens.Someone writes iterative pre-order but pushes the LEFT child first, then the right. On the same tree (4 with children 2 and 6, leaves 1, 3, 5, 7), what is printed?
out, stack = [], [root]
while stack:
node = stack.pop()
out.append(node.val)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
print(out)In-order: the go-left loop
In-order is not "pop and push children", because a node must wait until its whole left subtree is done. The loop above encodes that wait: push nodes while walking left, pop one when you hit the bottom, emit it, then step into its right subtree and repeat. The stack holds the nodes whose left side is in progress, which is exactly what the recursive calls were holding.
Walk left from the root, pushing each node: 4, 2, 1. Node 1 has no left child, so node becomes None and the inner loop stops.
Post-order three ways
Post-order (left, right, node) is the hardest to do iteratively, because a node is visited twice: once on the way down and once when both children are finished. There are three standard answers, and knowing all three is a strong signal.
- Reversed modified pre-order. Produce
node, right, left(push left, then right) and reverse the output. Short and correct, but it builds the whole output before you can use any of it, so it cannot stream and it cannot compute values bottom-up as it goes. - Visited flag. Push
(node, False). When popped with False, push(node, True)back, then the children. When popped with True, the children are done, so emit the node. This is the most general version, and it is the one that extends to return values. - One stack with a
lastpointer. Go left like in-order, then look at the top: if it has a right child you have not just finished, go right; otherwise emit and pop. O(h) memory, true post-order as it goes, but easy to get wrong under pressure.
Press Run (⌘ Enter) to see what happens.Simulating return values
Traversal order is half the job. Most tree recursion also returns something: a height, a sum, "is this subtree balanced". The parent uses its children's results. A loop has no return, so you need somewhere to put each result until the parent asks for it.
The visited-flag pattern gives you the moment ("both children are done"), and a dictionary gives you the place. Each frame is (node, state): state 0 means "not started, schedule my children", state 1 means "my children have finished, combine their answers".
Press Run (⌘ Enter) to see what happens.This is a general recipe, not a trick for heights. Any recursive function with several call sites can be converted the same way: give each "point where execution resumes" a state number, and store results where the next state can read them. The dictionary costs O(n) memory; if that matters, store each result on a small results stack instead, since children always finish right before their parent's combine step.
Graph DFS: where you mark changes the order
On a tree every node has one parent, so it cannot be reached twice. On a graph it can, so you need a seen set. When you add to it decides what you get.
- Mark on push. Add a node to
seenthe moment you push it. Each node enters the stack once, so the stack stays at O(V). It visits every reachable node, which is all you need for "is there a path", counting components or flood fill. But it is not the order recursion would produce: a node is claimed by whoever saw it first, even if a deeper path would have reached it earlier. - Mark on pop. Push freely, skip a node when popped if it is already seen. A node can be pushed several times (stack up to O(E)), but the order matches recursive DFS exactly when you push neighbours in reverse.
Press Run (⌘ Enter) to see what happens.C is the giveaway. Recursion reaches it through B. Mark-on-push claims it while expanding A, so when B is expanded, C is already taken and D comes out first.
Pop A. Mark-on-push marks both B and C now and pushes C, then B. C is claimed by A.
When order really matters: finish times
Topological sort and cycle detection need finish order: the moment a node's whole subtree of descendants is done. Neither version above records that. The faithful conversion stores what the recursive call kept in its locals: the node and how far it got through its neighbour list. A Python iterator holds that position for you.
Press Run (⌘ Enter) to see what happens.The for ... else runs the else only when the loop ends without break, which is exactly "this node has no unvisited neighbours left". The stack here is the true DFS path from the start to the current node, so for cycle detection in a directed graph, "neighbour is on the stack right now" is the back-edge test. In JavaScript, store an index instead of an iterator: [node, i], and increment i as you scan.
Match each need to the iterative form that fits it.
The BST iterator: a paused traversal
LeetCode's BST Iterator asks for next() and hasNext() on a binary search tree, with next() in amortised O(1) and O(h) memory. Flattening the tree into a list is O(n) memory, so it misses the point. The answer is the in-order loop, cut into pieces: the stack is the paused state.
Press Run (⌘ Enter) to see what happens.One next() can push many nodes, but each node is pushed and popped exactly once across the whole iteration, so n calls cost O(n) total: amortised O(1). The same shape is how real systems page through sorted data: a database cursor over a B-tree index keeps a path from the root, not a copy of the table. In Python you can also write this as a generator with yield, but generators that call themselves recursively still stack up frames, so for deep trees keep the explicit stack.
Memoised recursion to a bottom-up table
The Dynamic Programming lesson showed both styles on climbing stairs, where the fill order is obvious. The general rule is: fill a cell only after every cell it reads. Write down what each state depends on, then loop in the reverse of that dependency direction.
Here, best(r, c) is the cheapest cost from cell (r, c) to the bottom-right corner, moving right or down. It reads best(r + 1, c) and best(r, c + 1), both with bigger indices, so the table fills from the bottom-right, with both loops running backwards.
Press Run (⌘ Enter) to see what happens.The padding row and column of infinity replace the bounds checks: a move off the grid is never the cheapest. Two more things seniors keep in mind:
- The memoised version on a 1,000 by 1,000 grid recurses about 2,000 deep and fails in Python. The table version has no depth at all. This is the most common practical reason to convert.
- When the states form an arbitrary DAG (no simple index order, like "longest path in a dependency graph"), there is no pair of
rangeloops that works. Compute a topological order first, using the finish-order loop above, and fill in that order. Or keep the memo and drive it with an explicit stack.
Put the steps of converting a memoised recursion into a bottom-up table in order.
- Tap the steps below in the right order.
Morris traversal: in-order in O(1) extra space
Every method so far uses O(h) memory for the stack. Morris traversal uses none. It temporarily rewires the tree: before going into a node's left subtree, it points the rightmost node of that subtree (the in-order predecessor) back to the current node. That "thread" is the way back up that the stack used to provide. On the second arrival it removes the thread, so the tree is restored at the end.
Press Run (⌘ Enter) to see what happens.It is still O(n) time, since each edge is walked a constant number of times. Treat it as awareness: it mutates shared data (unsafe if another thread reads the tree, and broken if you stop half way), and interviewers rarely expect it unless they say "O(1) space". Knowing that it exists and how the thread works is usually enough.
When to keep the recursion
Converting is not always the right call. Recursive code is shorter and easier to review, and a balanced tree of a million nodes is only about 20 deep. Keep recursion when depth is bounded by something small and known: a balanced tree, a backtracking search over 15 choices, a parser for a format with a nesting limit. Convert when depth tracks the input size and the input comes from outside: user-built hierarchies, linked chains, graph paths, grids. In code review, "what is the maximum depth here, and who controls it?" is the question to ask.
- call frame
- What one function call keeps on the call stack: its arguments, local variables and where to resume.
- explicit stack
- A list you push and pop yourself to replace the call stack, so depth is limited by memory, not by the frame limit.
- tail-call optimisation
- Reusing the frame for a call in tail position. CPython and V8 do not do it, so tail recursion still overflows.
- mark on push vs pop
- When a graph DFS adds a node to seen. On push keeps the stack O(V) but changes order; on pop matches recursive DFS order.
- finish order
- The order in which DFS completes each node. Reversed, it is a topological order. Needs frames that remember their position.
- amortised O(1)
- Some calls cost more, but the total over n calls is O(n), as with BST iterator next().
- Morris traversal
- In-order in O(1) extra space by temporarily threading predecessors back to their ancestors.