Recursion Deep Dive — ELI5

You know those Russian nesting dolls? You open a big doll, and inside there is a smaller doll. Open that one, and there is an even smaller one inside. You keep opening dolls until you find the tiniest one that does not open — that is the last one.

Recursion is when a function calls itself, like opening a doll to find another doll inside. Each time it calls itself, the problem gets a little smaller. Eventually it hits the tiniest version of the problem — one so simple it can answer immediately, without calling itself again. That tiny problem is called the base case.

Here is a real example. Imagine you want to count how many blocks are in a tower of 5 blocks. You could say: “The tower of 5 is just 1 block sitting on top of a tower of 4.” And a tower of 4? That is 1 block on a tower of 3. And so on, until you get to a tower of 1 — that is just 1 block. Done. Now you add back up: 1 + 1 + 1 + 1 + 1 = 5.

That is exactly how recursion works:

  1. Break the problem down — make it one step smaller
  2. Trust that the smaller version works — this is the magic part
  3. Hit the base case — the simplest version you can answer directly
  4. Build the answer back up — combine the small answers into the full answer

Why is this useful? Because some problems are naturally shaped like nesting dolls. Family trees (each person has parents who have parents). File folders (a folder contains folders that contain folders). Fractals (patterns inside patterns inside patterns).

The tricky part is that you have to make sure you always reach the tiniest doll. If you forget the base case, the function keeps calling itself forever, like a mirror facing a mirror — an infinite tunnel that eventually crashes your program.

One thing to remember: Recursion is solving a problem by solving a smaller version of the same problem, until you reach a version so small that the answer is obvious.

pythonrecursionalgorithms

See Also