Recursive Fibonacci

Each fib(n) splits into fib(n−1) and fib(n−2). The call tree grows fast — and the same small values get computed over and over.

Programming Beginner Recursion · Call tree ~10 min
The idea

Two recursive calls, one tree

The Fibonacci sequence is 0, 1, 1, 2, 3, 5, …. Recursively: if n ≤ 1, return n; otherwise return fib(n − 1) + fib(n − 2).

Unlike factorial’s single chain, each call branches. Watch the tree fill in — then notice how many orange nodes redo work that was already finished elsewhere.

TipStart with fib(4). Then try fib(5) and count how many times fib(2) appears.
IdeaDefinition
fibonacci.pyPython
def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)

This version is correct but not efficient — the tree proves why.

Interactive

Run the simulation

Nodes stay on the tree after they return so you can compare identical subproblems side by side.

Step 0 / 0
fibonacci.pyPython
Call treefib(4)
Ready
Shortcuts: Space play/pause · → step · ← back · R reset
Remember

Why the naive tree wastes work

Correct answers, exponential cost — the overlapping subproblems are the lesson.

Branch

Two calls per step

Each non-base call opens fib(n−1) and fib(n−2), so the tree roughly doubles each level.

Overlap

Same fib(k) again

Orange nodes redo a value that already finished elsewhere. Nothing is remembered between branches.

Fix

Memoize or iterate

Store answers (memoization / DP) or build upward in a loop so each n is solved once.