Recursion is when a function calls itself. With each call, the function works on a simpler version of the original problem.
There are two parts to recursion:
- The base case: the simplest possible version of the problem
- The recursive case: where the function reduces the problem and calls itself again
So, the problem is broken down into smaller pieces until it reaches the simplest case, then the results are built back up from the inside out.
So what does this mean in plain English? Let's look at calculating factorials, a common way to teach recursion. A factorial means multiplying a number by every smaller whole number down to 1.
For example:
Here is a recursive version in Python:
The recursive version works like this:
When it reaches the bottom, the answers build back up:
Now compare that with a loop:
Recursive code is often simpler to read, but it is usually not faster. Each recursive call creates another stack frame. If there are too many recursive calls, the program can run out of stack space. For simple repetition, loops are usually better.
Recursion is most useful when the problem naturally breaks down into smaller versions of itself, such as:
- Searching a directory tree
- Traversing a tree structure
- Divide-and-conquer algorithms
- Exploring all possible paths in a maze or game