RevursionOpen the visualizer ↗

The Fibonacci recursion tree

Draw one node per function call. The children of fib(n) are fib(n − 1) and fib(n − 2). A node with input 0 or 1 has no children.

Trace fib(5) →

Walk through fib(5)

The first call waits for fib(4), which waits for fib(3). Continue down the left branches until fib(1) returns 1. The function then evaluates the other branch. Each parent adds the values it receives from its children.

fib(5) → 5
├─ fib(4) → 3
│  ├─ fib(3) → 2
│  └─ fib(2) → 1
└─ fib(3) → 2

The diagram shows the first two levels. The plain tree has 15 calls in all. The call count includes the original call and each repeated input.

See where memoization helps

Both branches need fib(3). Plain recursion evaluates both subtrees. With memoization, the second call reads the saved result and returns 2 immediately. Cache lookups still count as function calls in this visualizer.

InputResultPlain callsMemoized calls
fib(3)255
fib(5)5159
fib(8)216715

Try a trace you can explain

  1. Open memoized fib(5) and step until the first “From cache” node appears.
  2. Identify the earlier call that supplied its value.
  3. Switch to plain recursion, find the same repeated input and count how many child calls the second version makes.

For more on the difference between a recursive procedure and the process it generates, see Abelson and Sussman’s chapter on tree recursion.