Refinement into iterative algorithms
Introduction / Definition
Recursive algorithms can often be transformed into iterative ones by replacing implicit call-stack state with explicit state. This can avoid deep call stacks. Linear recursion may become a loop with an accumulator. Branching recursion often uses an explicit stack.
Syntax / Structure / Formula
recursive calls + call stack → loop/explicit stack + state
Detailed Explanation
For tree traversal, store nodes that would otherwise remain on the call stack in an explicit stack. Preserve the original processing order.
Example
Example: Recursive factorial becomes a loop multiplying an accumulator.
Output / Result
Both versions compute the same factorial result.
Important Points / Notes
- Explicit stacks replace branching recursion.
- Check order and termination.
Mini Practice Question
Why might iteration be preferred for very deep recursion?