Sub topic 9
Multiple Recursive Calls and Tree Recursion
This chapter assumes you can write a recursive function with a base case and a recursive case, and that you can trace calls on the call stack. Earlier chapters covered both. Every function so far made at most one recursive call per step, so its calls formed a single chain. Here we look at functions that make two or more recursive calls per step. Their calls branch out like a tree, and that changes both how they run and how much they cost.
From a Chain of Calls to a Tree of Calls
A function that calls itself once per step, such as factorial, produces a straight line of calls: factorial(5) calls factorial(4), which calls factorial(3), and so on down to the base case. The number of calls equals the depth of the recursion.
Tree recursion (also called multiple recursion) is recursion where one call can make two or more recursive calls. Each of those calls can branch again, so the full set of calls forms a tree. The classic example is the Fibonacci sequence, where each number is the sum of the two before it:
- fib(0) = 0
- fib(1) = 1
- fib(n) = fib(n − 1) + fib(n − 2) for n ≥ 2
The definition translates directly into code:
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10)) # 55The base case n < 2 covers both 0 and 1. The recursive case makes two calls, and both arguments are smaller than n, so every branch moves toward the base case.
Seeing the Call Tree
Here is every call that fib(4) makes. Each node is one call, and its children are the calls it makes.
The leaves are base cases. Each internal node adds the values returned by its two children. The root gets 3, which is fib(4).
The order calls actually run in
The tree shows all the calls, but Python does not run them at the same time. In the expression fib(n - 1) + fib(n - 2), Python evaluates the left operand first. The whole left subtree finishes before the right subtree starts. This is a depth-first walk of the tree. You can watch it happen by indenting each call by its depth:
def fib_trace(n, depth=0):
print(" " * depth + f"fib({n})")
if n < 2:
return n
return fib_trace(n - 1, depth + 1) + fib_trace(n - 2, depth + 1)
fib_trace(4)
# fib(4)
# fib(3)
# fib(2)
# fib(1)
# fib(0)
# fib(1)
# fib(2)
# fib(1)
# fib(0)The output reads like the diagram turned on its side, top to bottom and left to right.
Depth Versus Total Work
For linear recursion, stack depth and total calls are the same number. Tree recursion splits them apart, and you need to think about each one separately.
The call stack only holds the frames on the current path from the root to the call that is running. When fib(1) at the bottom-left runs, the stack holds fib(4), fib(3), fib(2), fib(1). When a call returns, its frame is popped and the next sibling's frame takes its place. The maximum stack depth for fib(n) is therefore about n, the height of the tree.
The total number of calls is the number of nodes in the tree, and that grows much faster. Count them directly:
calls = 0
def fib_counted(n):
global calls
calls += 1
if n < 2:
return n
return fib_counted(n - 1) + fib_counted(n - 2)
for n in (5, 10, 20, 25):
calls = 0
fib_counted(n)
print(n, calls)
# 5 15
# 10 177
# 20 21891
# 25 242785| n | Max stack depth | Total calls |
|---|---|---|
| 5 | 5 | 15 |
| 10 | 10 | 177 |
| 20 | 20 | 21,891 |
| 25 | 25 | 242,785 |
| 30 | 30 | 2,692,537 |
Each increase of 1 in n multiplies the call count by roughly 1.6. The call count follows the formula 2·fib(n + 1) − 1, so it grows exponentially. Running fib(40) this way takes hundreds of millions of calls, and a run of many seconds in CPython is normal.
Where the Waste Comes From
Branching by itself is not the problem. Look at the diagram again: fib(2) is computed twice, and fib(1) three times. The two branches overlap, because fib(n - 1) itself calls fib(n - 2), the same call the right branch is about to make. As n grows, the same small subproblems get solved again and again. In fib(n), the call fib(2) happens fib(n − 1) times.
Some tree recursions have no overlap. For example, a function that lists every binary string of length n makes two calls per step, but each branch builds different strings, so no work is repeated. It still makes an exponential number of calls, and that cost is unavoidable because the output itself has 2ⁿ strings.
def binary_strings(n):
if n == 0:
return [""]
shorter = binary_strings(n - 1)
return ["0" + s for s in shorter] + ["1" + s for s in shorter]
print(binary_strings(3))
# ['000', '001', '010', '011', '100', '101', '110', '111']This version calls itself once and reuses the result for both prefixes, which shows that you can sometimes remove the branching just by storing a result in a variable. When the overlap is spread across many separate calls, as in fib, you need a more general fix. A later chapter on memoization covers it.
| Situation | Example | Is the exponential cost necessary? |
|---|---|---|
| Branches solve the same subproblems | Naive `fib` | No. Caching results removes the repeated work |
| Branches produce different results | Listing subsets, permutations | Yes, the output itself is exponential in size |
| Branches split the input into disjoint parts | Merge sort, tree height | Usually no blowup, because each element is handled a bounded number of times per level |
Common Errors
A base case that misses a branch
When a function calls itself on n - 2, the base case must catch every value that can be reached. This version looks reasonable but never terminates for n = 1:
def fib_broken(n):
if n == 0:
return 0
return fib_broken(n - 1) + fib_broken(n - 2)
try:
fib_broken(1)
except RecursionError:
print("fib(1) calls fib(-1), which never reaches 0")fib_broken(1) calls fib_broken(-1), which keeps counting down past zero forever. If a call can step down by k at once, you need base cases that cover k consecutive values, or a guard such as n < 2 that catches everything below a threshold.
Estimating cost from stack depth
Testing with small inputs such as fib(10) finishes instantly, so the problem stays hidden until n reaches 35 or 40. Count calls, or draw a few levels of the tree, before trusting a tree-recursive function on large inputs.
Assuming both branches run at the same time
The two calls run one after another, left first. If the branches modify shared state, such as appending to a list, the left branch's changes are visible when the right branch starts. Backtracking relies on this order, as a later chapter shows.
Exercise
When computing fib(6) with the naive tree-recursive function, how many times is fib(2) called? What is the maximum stack depth, counting the fib(6) frame?
Show answer
fib(2) is called 5 times, because fib(2) runs fib(n − 1) times inside fib(n), and fib(5) = 5. The maximum depth is 6 frames: fib(6), fib(5), fib(4), fib(3), fib(2), fib(1) along the leftmost path.
Exercise
You can climb a staircase 1 or 2 steps at a time. Write a tree-recursive function ways(n) that returns how many distinct ways there are to climb n steps, and give ways(4).
Show answer
def ways(n): return 1 if n <= 1 else ways(n - 1) + ways(n - 2). Using n <= 1 as the base case handles both n = 0 (one way: do nothing) and n = 1. ways(4) = 5: 1111, 112, 121, 211, 22. The call tree has the same shape as fib's and the same repeated subproblems.
Exercise
A function f(n) returns 1 when n <= 0 and otherwise returns f(n - 1) + f(n - 1). Rewrite it to make one recursive call per step, and state how the number of calls changes.
Show answer
def f(n): if n <= 0: return 1; r = f(n - 1); return r + r. The original makes 2^(n+1) − 1 calls because both branches are identical. The rewrite makes n + 1 calls, because storing the result in a variable removes the duplicate branch.