CS205

Recursion vs Iteration

Compare recursive and iterative solutions side-by-side. See how they differ in code, complexity, and performance.

Factorial: Recursive vs Iterative
Recursive
int factorialRec(int n) {
    if (n <= 1) return 1;
    return n * factorialRec(n - 1);
}
Time: O(n)Space: O(n) - call stack
Iterative
int factorialIter(int n) {
    int result = 1;
    for (int i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}
Time: O(n)Space: O(1)
AspectRecursiveIterative
Time ComplexityO(n)O(n)
Space ComplexityO(n) - call stackO(1)
Code ClarityOften more intuitiveMore explicit control flow
Stack RiskStackOverflow possibleNo stack risk
Best ForTree structures, divide & conquerSimple loops, large inputs

Use Recursion When:

  • • Problem has natural recursive structure (trees)
  • • Code clarity is more important than performance
  • • Input size is bounded and small
  • • Divide & conquer approach needed

Use Iteration When:

  • • Simple linear traversal
  • • Performance is critical
  • • Very large input sizes expected
  • • Memory is constrained
Decision Guide: When to Use Each
SituationRecommendationWhy
Tree/graph traversalRecursionNatural tree structure maps to recursive calls
Simple counting/loopingIterationSimpler, no stack overhead
Divide and conquerRecursionProblem naturally splits into subproblems
Very large inputIterationAvoids stack overflow risk
Performance criticalIterationNo function call overhead
Code clarity importantDependsSometimes recursion is cleaner, sometimes iteration
Key Differences Summary

Recursion

  • Elegant for problems with recursive structure
  • Often more intuitive for tree-like problems
  • Can express complex logic concisely
  • Uses O(n) stack space
  • Function call overhead
  • Risk of stack overflow

Iteration

  • Uses O(1) space (usually)
  • No function call overhead
  • No stack overflow risk
  • Generally faster
  • Can be less intuitive for complex problems
  • May require explicit stack for tree-like problems
Final Tips

Start with Recursion, Optimize Later

If the problem has recursive structure, write the recursive solution first. It's often easier to get correct. Then optimize to iteration if needed.

Every Recursion Can Be Converted to Iteration

Any recursive algorithm can be written iteratively using an explicit stack. The question is whether the conversion improves clarity or performance.

Know Your Constraints

If input can be very large (n > 10,000), prefer iteration. If you're working with trees or graphs, recursion is often natural and safe.