Recursion and Backtracking Basics

Lesson 8 of 20

Watch factorial(4) stack four frames and unwind to 24 — then trace fibonacci’s tree as it recomputes the same values.

The big picture

Why recursion works

Recursion solves a problem by calling itself on a smaller copy — the call stack does the bookkeeping, and backtracking reuses the trick to explore choices.

A function calls itself

factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2)… every call works on a strictly smaller input.

The base case

factorial(1) returns 1 and stops the descent. No base case means frames pile up forever — stack overflow.

Every call gets a frame

The call stack hands each call its own private n. factorial(4) stacks 4 frames before the first one returns.

Unwinding

On the way back up, frames pop and results combine: 2 * 1 = 2, then 3 * 2 = 6, then 4 * 6 = 24.

Backtracking

Recurse into a choice, undo it, try the next — the engine behind subsets, permutations and maze solving.