Recursion solves problems by reducing them to smaller versions of the same problem. Every recursive function has a base case (terminates), a recursive case (calls itself with smaller input), and a combine step (merges results). .NET does not reliably tail-call optimise, so deep recursion risks StackOverflowException. Converting to an explicit Stack<T> removes the recursion limit. Memoization caches recursive results to avoid exponential recomputation.
Fibonacci without vs with memoization: O(2^n) vs O(n).
If the same input is computed more than once (Fibonacci, grid paths), add a Dictionary<int,int> cache. Instant transformation from exponential to linear.
Any recursion over user-controlled depth (file system, JSON, tree) must be iterative with explicit Stack<T> to prevent StackOverflowException.
Write the base case before the recursive case. Trace through the simplest input (n=0, n=1) before testing larger inputs.
Sign in to share your feedback and join the discussion.