Skip to content

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.

24 min read0/4 questions

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 get RecursionError: 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.
Python
import sys def depth(n): if n == 0: return 0 return 1 + depth(n - 1) old = sys.getrecursionlimit()print("default limit here:", old)sys.setrecursionlimit(300) # pretend the limit is smalltry: depth(1000)except RecursionError as e: print("RecursionError:", e)finally: sys.setrecursionlimit(old) # always put it back def depth_loop(n): count = 0 while n > 0: n -= 1 count += 1 return count print(depth_loop(1_000_000))
Output
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.

Quick check
A colleague says: 'I rewrote the walk as tail recursion, so the depth limit no longer applies in Python.' What is the right response?
Need a nudge? A hint rules out a wrong answer.

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:

  1. Decide what one frame needs to remember. Often just the node. Sometimes the node plus "how far through it am I".
  2. Push the starting frame onto a list.
  3. 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.

Python
class Node: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right # 4# 2 6# 1 3 5 7root = Node(4, Node(2, Node(1), Node(3)), Node(6, Node(5), Node(7))) def preorder(root): out, stack = [], [root] if root else [] while stack: node = stack.pop() out.append(node.val) if node.right: # pushed first, popped second stack.append(node.right) if node.left: # pushed last, popped next stack.append(node.left) return out def inorder(root): out, stack, node = [], [], root while stack or node: while node: # run down the left spine stack.append(node) node = node.left node = stack.pop() # leftmost unvisited node out.append(node.val) node = node.right # then its right subtree return out assert preorder(root) == [4, 2, 1, 3, 6, 5, 7]assert inorder(root) == [1, 2, 3, 4, 5, 6, 7]assert preorder(None) == [] and inorder(None) == [] # a 100,000-node chain: recursion would die, the loops do not carechain = Nonefor v in range(100_000, 0, -1): chain = Node(v, left=chain)assert inorder(chain)[:3] == [100_000, 99_999, 99_998]assert len(preorder(chain)) == 100_000print(preorder(root), inorder(root))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

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)
Need a nudge? Hints walk you through it.

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.

Iterative in-order on 4 (2 (1, 3), 6 (5, 7))
4
0
2
1
1
2
node = Noneoutput =

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.

1/6

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 last pointer. 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.
Python
class Node: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right root = Node(4, Node(2, Node(1), Node(3)), Node(6, Node(5), Node(7))) def post_reversed(root): # node, right, left ... then reverse it: left, right, node out, stack = [], [root] if root else [] while stack: node = stack.pop() out.append(node.val) if node.left: stack.append(node.left) if node.right: stack.append(node.right) return out[::-1] def post_flag(root): out, stack = [], [(root, False)] if root else [] while stack: node, children_done = stack.pop() if children_done: out.append(node.val) # second visit: children finished else: stack.append((node, True)) # come back to me after... if node.right: stack.append((node.right, False)) if node.left: stack.append((node.left, False)) # ...left, then right return out def post_prev(root): # one stack, O(h) memory, emits nodes in true post-order as it goes out, stack, node, last = [], [], root, None while stack or node: while node: stack.append(node) node = node.left top = stack[-1] if top.right and top.right is not last: node = top.right # right subtree not done yet else: out.append(top.val) last = stack.pop() return out expected = [1, 3, 2, 5, 7, 6, 4]for f in (post_reversed, post_flag, post_prev): assert f(root) == expected, f.__name__ assert f(None) == []print(expected)
Output
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".

Python
class Node: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def height_rec(node): if node is None: return 0 return 1 + max(height_rec(node.left), height_rec(node.right)) def height_iter(root): # Each frame is (node, state). state 0: children not started. # state 1: children finished, their answers are in `result`. result = {None: 0} stack = [(root, 0)] while stack: node, state = stack.pop() if node is None: continue if state == 0: stack.append((node, 1)) stack.append((node.right, 0)) stack.append((node.left, 0)) else: result[node] = 1 + max(result[node.left], result[node.right]) return result[root] root = Node(1, Node(2, Node(4), Node(5, Node(7))), Node(3))assert height_rec(root) == height_iter(root) == 4assert height_iter(None) == 0 chain = Nonefor v in range(50_000): chain = Node(v, right=chain)assert height_iter(chain) == 50_000print(height_iter(root), height_iter(chain))
Output
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 seen the 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.
Python
graph = {"A": ["B", "C"], "B": ["C", "D"], "C": [], "D": []} def dfs_recursive(start): seen, order = set(), [] def visit(u): seen.add(u) order.append(u) for v in graph[u]: if v not in seen: visit(v) visit(start) return order def mark_on_push(start): seen, stack, order = {start}, [start], [] while stack: u = stack.pop() order.append(u) for v in reversed(graph[u]): if v not in seen: seen.add(v) # claimed now, by whoever saw it first stack.append(v) return order def mark_on_pop(start): seen, stack, order = set(), [start], [] while stack: u = stack.pop() if u in seen: # stale duplicate entry, skip it continue seen.add(u) order.append(u) for v in reversed(graph[u]): if v not in seen: stack.append(v) return order print("recursive ", dfs_recursive("A"))print("mark on push", mark_on_push("A"))print("mark on pop ", mark_on_pop("A"))assert mark_on_pop("A") == dfs_recursive("A")
Output
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.

Why mark-on-push visits D before C
ABCD

currentwaitingdone

Pop A. Mark-on-push marks both B and C now and pushes C, then B. C is claimed by A.

1/4

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.

Python
def finish_order(graph, start): # Each frame holds a node and an iterator over its neighbours: # exactly what a recursive call keeps in its local variables. seen, done = {start}, [] stack = [(start, iter(graph[start]))] while stack: u, neighbours = stack[-1] for v in neighbours: # resume where this frame left off if v not in seen: seen.add(v) stack.append((v, iter(graph[v]))) break # "call" v; come back to u later else: # no neighbours left: "return" stack.pop() done.append(u) return done # course -> courses that depend on itgraph = {"intro": ["data", "web"], "data": ["ml"], "web": ["ml"], "ml": []}order = finish_order(graph, "intro")print("finish order:", order)print("topological :", order[::-1])assert order == ["ml", "data", "web", "intro"] # a 200,000-node path: a recursive version would need 200,000 framespath = {i: [i + 1] for i in range(200_000)}path[200_000] = []assert finish_order(path, 0)[0] == 200_000
Output
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 the pairs0/5 matched

Match each need to the iterative form that fits it.

Choose an item, then its match on the other side.

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.

Python
class Node: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right class BSTIterator: def __init__(self, root): self.stack = [] self._push_left(root) def _push_left(self, node): while node: self.stack.append(node) node = node.left def peek(self): return self.stack[-1].val def has_next(self): return bool(self.stack) def next(self): node = self.stack.pop() self._push_left(node.right) # the in-order loop, paused return node.val root = Node(7, Node(3), Node(15, Node(9), Node(20)))it = BSTIterator(root)out = []while it.has_next(): out.append(it.next())assert out == [3, 7, 9, 15, 20] # merge two BSTs in sorted order, one value at a timedef merge(a, b): out = [] while a.has_next() or b.has_next(): if not b.has_next() or (a.has_next() and a.peek() <= b.peek()): out.append(a.next()) else: out.append(b.next()) return out merged = merge(BSTIterator(Node(2, Node(1), Node(4))), BSTIterator(Node(1, None, Node(3))))assert merged == [1, 1, 2, 3, 4]print(out, merged)
Output
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.

Python
from functools import cache grid = [ [1, 3, 1, 8], [1, 5, 1, 2], [4, 2, 1, 9],]R, C = len(grid), len(grid[0]) @cachedef best(r, c): # cheapest cost from (r, c) to the bottom-right, moving right or down if r == R - 1 and c == C - 1: return grid[r][c] options = [] if r + 1 < R: options.append(best(r + 1, c)) if c + 1 < C: options.append(best(r, c + 1)) return grid[r][c] + min(options) def best_table(): INF = float("inf") dp = [[INF] * (C + 1) for _ in range(R + 1)] # padding row and column for r in range(R - 1, -1, -1): # best(r, c) needs r + 1... for c in range(C - 1, -1, -1): # ...and c + 1, so go backwards if r == R - 1 and c == C - 1: dp[r][c] = grid[r][c] else: dp[r][c] = grid[r][c] + min(dp[r + 1][c], dp[r][c + 1]) return dp[0][0] assert best(0, 0) == best_table() == 16print(best(0, 0), best_table())
Output
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 range loops 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 it in order5 steps

Put the steps of converting a memoised recursion into a bottom-up table in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
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.

Python
class Node: def __init__(self, val, left=None, right=None): self.val, self.left, self.right = val, left, right def morris_inorder(root): out, node = [], root while node: if node.left is None: out.append(node.val) node = node.right continue pred = node.left # rightmost node of the left subtree while pred.right and pred.right is not node: pred = pred.right if pred.right is None: pred.right = node # thread: a way back up node = node.left else: pred.right = None # second arrival: remove the thread out.append(node.val) node = node.right return out root = Node(4, Node(2, Node(1), Node(3)), Node(6, Node(5), Node(7)))assert morris_inorder(root) == [1, 2, 3, 4, 5, 6, 7]assert morris_inorder(root) == [1, 2, 3, 4, 5, 6, 7] # tree restored, runs againprint(morris_inorder(root))
Output
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.

Key terms
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.