Sub topic 7
Drawing Recursion Trees to Count Work
A recursive function can look short and harmless while doing an enormous amount of work. The quickest way to see how much work it does is to draw its recursion tree: a picture in which every call is a node and every call that a function makes is an edge to a child node. This chapter shows how to draw these trees, how to read running time and stack depth from them, and which tree shapes come up again and again.
This chapter assumes you can write recursive functions with a base case and a recursive case, that you know how the call stack holds one frame per active call, and that you can read Big-O notation.
What a Recursion Tree Records
Each node in a recursion tree stands for one call, labeled with its arguments. A node's children are the recursive calls made directly inside that call, in the order they happen. Base-case calls are the leaves because they make no further calls.
The tree answers two separate questions:
| Question | Where to look in the tree | What it measures |
|---|---|---|
| How many calls happen in total? | Number of nodes | Running time (when each call does constant work) |
| How much stack is needed at once? | Height of the tree (longest root-to-leaf path) | Maximum recursion depth, i.e. stack space |
| How much work happens overall? | Sum of the non-recursive work over all nodes | Running time in general |
Keep time and stack space apart. A tree can have millions of nodes and still be shallow. Python only keeps the frames along one root-to-leaf path alive at any moment, so stack usage follows the height. Time follows the total node count.
The Chain: One Recursive Call per Level
Recursive factorial makes exactly one recursive call per invocation. Its tree has no branching. It is a single chain:
For input n the chain has n + 1 nodes, and each node does one multiplication plus a comparison. The time is O(n). The height is also n + 1, so the stack depth is O(n). A chain is the case where node count and height are the same number.
Branching: Two Calls per Level
Now consider a function that calls itself twice on n - 1:
def double(n):
if n == 0:
return 1
return double(n - 1) + double(n - 1)
print(double(3)) # 8It returns 2ⁿ. Its tree doubles in width at every level:
To count the nodes, count level by level. Level k (with the root at level 0) has 2ᵏ nodes, and the levels run from 0 to n:
1 + 2 + 4 + … + 2ⁿ = 2ⁿ⁺¹ − 1
So double(n) makes 2ⁿ⁺¹ − 1 calls, which is O(2ⁿ) time. The height is still only n + 1, so the stack depth is O(n). The tree is exponentially wide but only linearly deep. This is why exponential recursions usually run "forever" instead of crashing with a stack overflow.
Spotting repeated labels
Look at the labels in the diagram: double(2) appears twice, double(1) four times, and double(0) eight times. Every repeated label is a subproblem being solved again from scratch. The fix in this case is easy. Compute the subcall once and reuse it:
def double_fast(n):
if n == 0:
return 1
half = double_fast(n - 1)
return half + half
print(double_fast(3)) # 8The answer is identical, but the tree collapses back into a chain of n + 1 nodes. Whenever a tree has many identical labels, look for a way to compute each distinct label only once. Later chapters return to this idea with Fibonacci, where the repeated subproblems are not identical siblings, so the fix needs more work.
Shrinking by Halving
The size of the argument matters as much as the number of calls. When each call divides n by 2 instead of subtracting 1, the tree is only about log₂ n levels tall.
With one call per level, the tree is a short chain:
def split_one(n):
if n <= 1:
return 1
return split_one(n // 2)For n = 16 the chain is 16 → 8 → 4 → 2 → 1: five calls. In general it makes ⌊log₂ n⌋ + 1 calls, so it runs in O(log n) time with O(log n) depth.
With two calls per level, the widths double while the arguments halve:
def split_two(n):
if n <= 1:
return 1
return split_two(n // 2) + split_two(n // 2)For n = 16 the levels hold 1, 2, 4, 8, and 16 nodes, 31 calls in total. When n is a power of two the count is 2n − 1. The tree doubles in width on each of its log₂ n levels, and 2^(log₂ n) = n, so the time is O(n) even though the depth is only O(log n).
Exponentiation by squaring, covered later in the tutorial, uses the split_one shape. That is where its logarithmic cost comes from.
Measuring Instead of Guessing
You can check any count you derive by instrumenting the functions. The script below counts calls for all four tree shapes at n = 16:
from collections import Counter
calls = Counter()
def chain(n):
calls["chain"] += 1
if n == 0:
return 0
return chain(n - 1)
def double(n):
calls["double"] += 1
if n == 0:
return 1
return double(n - 1) + double(n - 1)
def split_two(n):
calls["split_two"] += 1
if n <= 1:
return 1
return split_two(n // 2) + split_two(n // 2)
def split_one(n):
calls["split_one"] += 1
if n <= 1:
return 1
return split_one(n // 2)
for f in (chain, double, split_two, split_one):
calls.clear()
f(16)
print(f"{f.__name__:>10}: {calls[f.__name__]} calls")Output:
chain: 17 calls
double: 131071 calls
split_two: 31 calls
split_one: 5 callsEach number matches its formula: n + 1 = 17, 2¹⁷ − 1 = 131071, 2·16 − 1 = 31, and log₂ 16 + 1 = 5.
| Shape | Calls per node | Argument shrinks by | Nodes | Height |
|---|---|---|---|---|
| Chain | 1 | − 1 | O(n) | O(n) |
| Binary, subtract | 2 | − 1 | O(2ⁿ) | O(n) |
| Binary, halve | 2 | ÷ 2 | O(n) | O(log n) |
| Chain, halve | 1 | ÷ 2 | O(log n) | O(log n) |
When Nodes Do More Than Constant Work
Counting nodes gives the running time only when every call does O(1) work outside its recursive calls. If a call also loops over its input, give each node a cost and add the costs up level by level.
Suppose split_two also ran a loop of n steps in each call. The root costs n. Its two children cost n/2 each, which is n for that level. Each of the four grandchildren costs n/4, which is again n for the level. Every one of the log₂ n + 1 levels sums to n, so the total is O(n log n). Merge sort has this cost for exactly this reason. Summing per level works well because the nodes on one level usually all cost the same.
Common Mistakes
- Counting levels instead of nodes. The height of
double(n)is n + 1, but its time is 2ⁿ⁺¹ − 1 calls. Height tells you about stack space and node count tells you about time. - Forgetting the leaves. Base-case calls still cost time. In a full binary tree, the leaves make up about half of all nodes.
- Assuming every level is full. The level-by-level sum 1 + 2 + 4 + … assumes every branch reaches the same depth. If one branch shrinks faster than the other, as in
f(n - 1) + f(n - 2), the tree is lopsided. Bound it from above and below instead of using the full-tree formula. - Treating a variable reference as a call. In
double_fast,half + halfmakes one call, not two. Draw an edge only where the function is actually invoked.
Exercise
A function triple(n) returns 1 when n == 0 and otherwise returns triple(n - 1) + triple(n - 1) + triple(n - 1). How many calls does triple(n) make in total, and what is its maximum recursion depth?
Show answer
Level k has 3^k nodes for k = 0..n, so the total is (3^(n+1) − 1) / 2 calls, which is O(3^n). The tree is n + 1 levels tall, so the maximum recursion depth is n + 1 frames, which is O(n).
Exercise
Draw (or describe) the recursion tree for split_two(8). How many nodes does it have, and how many of them are leaves?
Show answer
The levels have arguments 8; 4, 4; four 2s; eight 1s. That is 1 + 2 + 4 + 8 = 15 nodes, which matches 2n − 1 for n = 8. The eight calls split_two(1) are the leaves.
Exercise
Rewrite split_two so that it returns the same value but makes only O(log n) calls. Why does this change the tree's shape?
Show answer
Store the result of one recursive call and reuse it: def split_two(n): if n <= 1: return 1; half = split_two(n // 2); return half + half. Each call now makes one recursive call instead of two, so the binary tree becomes a chain of about log2 n + 1 nodes.