Recursion is a problem solving method. In code, recursion is implemented using a function that calls itself.
Any iterative algorithm can be written recursively.
Iterative algorithms use for
loops and while
loops to simulate repetition. Recursive algorithms use function calls to simulate the same logic.
Base cases are conditions at the start of recursive functions that terminate the calls.
- Think from one level above the base case. Think from leaf node’s perspective.
Where recursion shines is when you use it to break down a problem into “subproblems”, whose solutions can then be combined to solve the original problem.
Tail call optimization: