advertisement

Recursion Visualizer

Watch recursive calls unfold and backtrack with step-by-step visualization.

Call Tree

See the recursion tree

Drilling Down

Watch calls expand

Backtracking

See values return

Stack Depth

Understand call stack

Settings

Code

function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}

Recursion Tree

Step 0 / 0

Current Step

Click "Visualize" to see the recursion unfold.

Call Stack

Understanding Recursion

  • Base Case: When to stop recursing
  • Recursive Case: Call itself with smaller input
  • Stack: Each call adds a frame
  • Return: Values bubble back up

Common Pitfalls

  • Missing base case �?Stack overflow
  • Wrong base case �?Infinite recursion
  • Not progressing toward base case
  • Excessive recursion depth

Examples & Anti-patterns

Good Practice

Tail Recursion Optimization

When the recursive call is the last operation, some engines can optimize to prevent stack growth.

// Tail recursive version
function factorial(n, acc = 1) {
  if (n <= 1) return acc;
  return factorial(n - 1, n * acc);
}
// Stack doesn't grow with n
Common Mistake

Exponential Time Fibonacci

Naive Fibonacci makes redundant calls, leading to O(2^n) time complexity.

// Bad: O(2^n) - many duplicate calls
function fib(n) {
  if (n <= 1) return n;
  return fib(n-1) + fib(n-2);
}
// Use DP/memoization instead!

Frequently Asked Questions

Use recursion for naturally recursive structures (trees, graphs) and when it makes code clearer. Use iteration when performance is critical or stack depth is a concern.

Use an explicit stack data structure. Push items instead of making recursive calls, and pop to process. This simulates the call stack manually.

Memoization caches results of expensive function calls. For recursive functions with overlapping subproblems (like Fibonacci), it can reduce complexity from exponential to linear.