Recursion trees
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
A recursion tree is a drawing of who called whom when a function keeps calling itself. Each call is a dot, and its helper calls hang below it. Counting the dots shows how much work the function really does, and where it repeats itself needlessly.
Practical use cases
- Web app: Fibonacci code that takes minutes. A developer writes a recursive function for a growth-pattern calculator and it hangs on input 45. Drawing the tree shows the same small calls repeated millions of times. Seeing this, they store results already calculated, and the page answers instantly.
- Web app: Discount combination finder. A coupon page tries each coupon on or off to find the best saving. Every coupon doubles the number of branches, so 10 coupons give about a thousand paths and 30 coupons give over a billion. The tree explains why the page freezes and warns you to limit or prune options.
- System: Merge sort cost. Merge sort splits a list in half, again and again. The tree has only about 20 levels for a million items, and each level touches every item once. That picture is why sorting a big list this way stays fast.
The story: The Family Tree of Calls
At Zoya's cousin's wedding, the family album had a huge family tree pinned on the wall. Grandpa Bhaskar sat at the top. Below him, his two sons. Below each son, their own children, and so on, branching down like a banyan turned upside-down.
Aarav, who was learning recursion, whispered, "My Fibonacci function is just like this tree!" The function fib(4) asks two helpers: fib(3) and fib(2). Each helper asks two more helpers. Draw every call as a person and every "asked by" as a line, and you get a recursion tree.
Mira counted names on the family tree to know how many relatives to feed. In the same way, she counted the nodes of Aarav's tree to learn how much work his function does. "Wait, Aarav, I can see fib(2) twice! You are doing the same job in two places."
That is the power of a recursion tree. Before running any code, you can sketch the calls, count the nodes for total work, measure the height for stack depth, and spot repeated work. Later, that repeated work is what memoization will fix.
How to spot this problem, and where you need it
A recursive function runs fast for small inputs but takes forever for slightly larger ones, and you cannot see why, or you need to estimate the cost before running it.
Signs you need it
- Adding one more item to the input makes the run time double, or far worse than double.
- The function calls itself two or more times per call, such as f(n-1) plus f(n-2).
- When you print the arguments of each call you see the same values appearing again and again.
Where to use it in a project
- Debugging recursive pricing, route or option-combination code that suddenly slows down on real data.
- Deciding whether to add caching to a recursive function, or whether a divide-and-conquer approach is cheap enough.
The solution
Draw the first few calls on paper: the starting call at the top, a branch for each call it makes. Note how many branches each dot has and how many levels it has. Multiply to estimate the total dots. If the same dot appears in many places, remember its answer in an array and reuse it. If the branches shrink quickly, such as halving, the tree is small and the code is fine.
Payoff: Before: a recursive calculation for 45 takes minutes with billions of calls. After: with remembered answers it needs about 45 calls and is instant.
Explain it like I am 8
Imagine you ask two friends for help, and each of them asks two more friends, and so on. Draw dots for everyone who was asked and lines for who asked whom. That drawing is a recursion tree, and counting dots tells you how busy everyone got.
How it works, step by step
- Draw the first call at the top as the root node, labelled with its input.
- For every recursive call it makes, draw a child node below it, and connect them with a line.
- Repeat for each child until you reach base cases, which have no children (leaves).
- Measure the height: this is the deepest the call stack ever gets.
- Count the nodes: this is the total number of calls, roughly the time cost. Look for the same label appearing twice, which signals wasted repeated work.
The code in four languages
PHP
<?php
$calls = 0;
// Print the recursion tree of fib(n), indenting each level.
function fib(int $n, int $depth = 0): int {
global $calls;
$calls++;
echo str_repeat(' ', $depth) . "fib($n)
";
if ($n < 2) return $n; // leaf of the tree
return fib($n - 1, $depth + 1) + fib($n - 2, $depth + 1);
}
$answer = fib(4);
echo "answer = $answer, calls (nodes in the tree) = $calls
";JavaScript
let calls = 0;
// Print the recursion tree of fib(n), indenting each level.
function fib(n, depth = 0) {
calls++;
console.log(" ".repeat(depth) + "fib(" + n + ")");
if (n < 2) return n; // leaf of the tree
return fib(n - 1, depth + 1) + fib(n - 2, depth + 1);
}
const answer = fib(4);
console.log("answer = " + answer + ", calls (nodes in the tree) = " + calls);Java
public class Main {
static int calls = 0; // counts every node of the tree
// Print the recursion tree of fib(n), indenting each level.
static int fib(int n, int depth) {
calls++; // one more call = one more node
System.out.println(" ".repeat(depth) + "fib(" + n + ")");
if (n < 2) return n; // leaf of the tree
return fib(n - 1, depth + 1) + fib(n - 2, depth + 1);
}
public static void main(String[] args) {
int answer = fib(4, 0);
System.out.println("answer = " + answer + ", calls (nodes in the tree) = " + calls);
}
}Go
package main
import (
"fmt"
"strings"
)
var calls = 0 // counts every node of the tree
// fib prints the recursion tree of fib(n), indenting each level.
func fib(n, depth int) int {
calls++ // one more call = one more node
fmt.Printf("%sfib(%d)\n", strings.Repeat(" ", depth), n)
if n < 2 {
return n // leaf of the tree
}
return fib(n-1, depth+1) + fib(n-2, depth+1)
}
func main() {
answer := fib(4, 0)
fmt.Printf("answer = %d, calls (nodes in the tree) = %d\n", answer, calls)
}Time: Exponential: the tree roughly doubles each level · Extra space: O(n) (height of the tree). Time equals the number of nodes in the tree, space equals its height, because only one root-to-leaf path is on the stack at a time.
Watch out for
- Thinking the stack holds the whole tree. It holds only one branch (root to the current node) at a time.
- Counting only the leaves instead of every node when estimating work.
- Missing repeated nodes. The same label twice is a clue that caching would help.
Quick check
- In a recursion tree, what does a node represent?
- A variable
- One call of the function
- A loop
- What does the height of the tree tell you?
- The deepest the call stack gets
- The number of leaves
- The answer
- You see fib(2) drawn twice in the tree. What does it suggest?
- A bug
- Repeated work that memoization could save
- The tree is balanced