Recursion and Backtracking Basics

Lesson 8 of 20

Watch the call stack pile up and unwind digitSum frames — then follow fib(4) through every branch of its recursion tree.

The big picture

The big picture

Recursion is a method that calls itself on a smaller piece of the problem. The base case stops the descent; the call stack assembles the answer on the way back up.

A method that calls itself

digitSum(472) peels off one digit (472 % 10 = 2) and hands 47 to a fresh copy of itself — same method, smaller problem.

The base case is the brakes

A single digit (n < 10) is answered directly with no further calls. Miss the base case and Java throws StackOverflowError, not an infinite loop.

The JVM call stack pays

Every call pushes a frame holding its own n. digitSum(472) stacks 3 frames — depth grows with the input, one frame per level.

The unwind

Answers are assembled on the way back up: 4 returns, then 7 + 4 = 11, then 2 + 11 = 13. Work after the call runs in reverse order.

Backtracking = try, recurse, undo

Listing subsets of {4, 9} branches at every item — take it or skip it — 2 choices squared is 4 outcomes, and each choice is undone before trying the other branch.

Naive recursion repeats work

fib(4) makes 9 calls and computes fib(2) twice. fib(30) would make over 2.6 million calls — memoization (a later topic) fixes that.