"Recursion and iteration aren't rivals — they're two ways to write the same computation. One uses the call stack; the other uses a loop (and sometimes your own stack). Knowing how to translate between them is a quiet superpower."
Anything Recursive Can Be Iterative
Every recursion can be rewritten as iteration, and vice versa — they're computationally equivalent. The reason is the call stack: recursion uses it implicitly, and iteration with an explicit stack does the exact same bookkeeping by hand. Simple linear recursions (factorial, summing a list) convert to plain loops with an accumulator. Branching recursions (tree and graph traversals) convert to loops driven by an explicit stack — precisely the stack-vs-recursion equivalence you met in the Stacks and Graphs tracks. The logic is identical; only who manages the stack changes.
When (and Why) to Convert
If recursion reads more clearly — and for tree-shaped problems it usually does — keep it. Convert to iteration when you have a concrete reason:
- Depth safety: recursion that could go thousands deep will hit Python's recursion limit; an explicit-stack loop on the heap won't. (The biggest reason in Python, which has no tail-call optimization.)
- Performance: function-call overhead is real; a tight loop can be meaningfully faster on hot paths.
- Tail recursion: a recursion whose last act is the recursive call is trivially a
whileloop — and since Python won't optimize it for you, you do it by hand.
The judgment: recursion for clarity, iteration for depth-safety and speed. Neither is 'better' — they're tools, and fluency means translating freely between them.
The Bridge to Dynamic Programming
Here's the conversion that opens the next track. Recall the Fibonacci catastrophe: recursion + a cache (memoization) collapsed O(2ⁿ) to O(n) — that's top-down DP, recursion that remembers. Now turn it inside out: instead of recursing down and caching, build the answers up from the base cases in a loop, filling a table. That's bottom-up tabulation — the iterative twin of memoized recursion. Memoized recursion and tabulation compute the same thing from opposite directions, and recognizing that recursion-with-a-cache can become a bottom-up loop is the doorway into dynamic programming, the very next track.