Draw the recursion tree and add up its cost.
Use it when a function calls itself, and you want to know how long it runs. Signal words: a function that calls itself twice, how many calls, draw the tree.
Draw one node for each call, with the size on it. Mark the leaves.
Count the calls on each level, by running the function with a counter on small inputs, or by the rule: calls = 1 + the calls of the children.
Add up for each level, the calls times the work of one call. Add the levels.
Compare the calls with the different questions, and the depth with the limit.
In this lesson you learn to draw the tree of calls that a recursion makes. You count its calls by running a little instrumented code, and you read its cost as the calls times the work of one call. You also learn why the number of calls and the depth of the stack are different.
You work on the reply ranking of a social app. The weight of a thread n levels deep is the weight at n - 1 levels, plus the weight at n - 2 levels. The weight is 1 for 0 and 1 levels.
A first version is a function that calls itself twice.
Your team lead says: The weight runs in the request path, for threads up to 45 levels deep. Is it fast enough?
Here is a short test: weight(5) is 8. The function makes 15 calls to get it, and 5 levels are not many.
So the task is this: find out how many calls weight(n) makes, and what that costs.
A club tells its members about a change with a phone tree. The chair phones two members. Each of them phones two more, and so on, until everyone has heard.
Each phone call is a node. A member who has no one left to phone ends the branch. After 5 rounds, the club has made 62 calls, and the news has gone no deeper than 5 members in a row.
The number of calls and the number of rounds are different numbers. Each call is a node of the tree, and the rounds are its levels. The cost of the evening is the number of calls, not the number of rounds.
A club phone tree: each call is a node, the evening costs the calls, and the news only goes a few rounds deep.
Before you write code, draw the calls of a small case by hand. It shows how the count grows.
Solve it by hand: weight(3): count every call. The hand-solve sheet loads in your browser.
You write one box for each call, and under it the two calls it makes. A call on 0 or 1 makes no calls: it is a leaf.
The call weight(3) makes weight(2) and weight(1). The call weight(2) makes weight(1) and weight(0). Each row is one call, in the order the calls start.
| Call number | Call | Makes | Calls so far |
|---|---|---|---|
| 1 | weight(3) | weight(2), weight(1) | 1 |
| 2 | weight(2) | weight(1), weight(0) | 2 |
| 3 | weight(1) | none: a leaf | 3 |
| 4 | weight(0) | none: a leaf | 4 |
| 5 | weight(1) | none: a leaf | 5 |
The call weight(3) makes 5 calls in all. The call weight(1) appears twice, so its work is done twice. Draw weight(4) and you find 9 calls.
Start with a correct version. It reads like the rule.
def weight(n):
if n < 2: # a leaf: it answers at once
return 1
return weight(n - 1) + weight(n - 2) # two calls, one for each smaller questionThis is correct. The team keeps it as the reference. The question is how long it takes on the largest input.
Now check the real size.
Threads reach 45 levels, and a request has a budget of 100 milliseconds.
Run the function with a counter, in Python, and look at the numbers:
weight(10) makes 177 calls, and weight(20) makes 21,891.weight(30) makes 2,692,537 calls, in about 70 milliseconds on the laptop used for this lesson.weight(37) makes 78,176,337 calls, in about 2 seconds. That is about 38 million calls a second.At that speed, weight(45) makes 3,672,623,805 calls and needs about 95 seconds. The budget is 100 milliseconds.
Predict the calls
Q You know that weight(30) makes about 2.7 million calls. Each step up from n to n + 1 multiplies the calls by about 1.6. About how many calls does weight(40) make?
Answer: C
Ten steps multiply the calls by 1.6 ten times, which is about 110. So 2.7 million becomes about 300 million. The exact count is 331,160,281.
The first attempt is correct, and it misses the budget by a factor of about 950. Now the team needs to understand where the calls come from.
Look at the calls of weight(5) as a tree. This picture is the recursion tree. The root is weight(5). Each call has two children, weight(n - 1) and weight(n - 2), until it reaches a leaf.
Draw one node for each call: the leaves answer at once, and the same call appears again and again.
Count the nodes level by level. The tree of weight(5) has 15 nodes: 1 call at the top, 2 below it, 4 on the next level, then 6 and 2. The longest path has 5 nodes, so the stack is never deeper than 5.
Now look for repeats. The call weight(3) appears twice, weight(2) three times, and weight(1) five times. Only 6 different questions exist, 0 to 5, and the tree asks 15.
The count follows the same rule as the function. A call counts itself, plus every call under weight(n - 1), plus every call under weight(n - 2). So calls(n) = 1 + calls(n - 1) + calls(n - 2), with 1 call for 0 and for 1.
Race: Calls made by the recursion, against the different questions it asks. The operation counter loads in your browser.
The race counts the calls by running the instrumented function, and compares them with the number of different questions. For n = 30 the recursion makes 2,692,537 calls to answer 31 different questions. Each step in n adds one question and multiplies the calls by about 1.6.
The call is weight(5). The player stops at five steps and asks you to predict.
Dry run: Predict each step: the calls of weight(5). The step-by-step player loads in your browser.
Reading without the player? Cover the last column and predict it row by row.
| Step | Call | Calls so far | Calls made by this call |
|---|---|---|---|
| 1 | weight(5) opens | 1 | not known yet |
| 2 | weight(4) opens | 2 | not known yet |
| 3 | weight(3) opens | 3 | not known yet |
| 4 | weight(2) opens | 4 | not known yet |
| 5 | weight(1), a leaf | 5 | 1 |
| 6 | weight(0), a leaf | 6 | 1 |
| 7 | weight(2) closes | 6 | 3 |
| 8 | weight(1), a leaf | 7 | 1 |
| 9 | weight(3) closes | 7 | 5 |
The calls of the last frames are 9 for weight(4) and 15 for weight(5). The call counts are 1, 1, 3, 5, 9, 15: each one is 1 plus the two before it.
The stack holds one path of the tree at a time, so its depth is the length of the longest path. The calls are all the nodes. For weight(40) the tree has 331,160,281 nodes, and the stack is only 40 frames deep. The number of calls decides the time, and the depth decides the memory on the stack.
Exercise · Predict the output: Calls and frames of weight(6). The code counts every call, and the deepest the calls nest, with weight(6). It starts at depth 1 for the first call. What does it print: the calls, then the depth?
calls = 0
deepest = 0
def weight(n, depth):
global calls, deepest
calls += 1
deepest = max(deepest, depth)
if n < 2:
return 1
return weight(n - 1, depth + 1) + weight(n - 2, depth + 1)
weight(6, 1)
print(calls, deepest)Here is the rule that keeps the count correct. Every line of the template exists to protect it.
The cost of a recursion is the sum, over the levels of its tree, of the calls on a level times the work of one call.
A level is every node at the same distance from the root. The calls on a level are all different calls, so their work adds up. Adding the levels adds every call exactly once, so the sum is the whole cost.
When the work of a call is constant, each level costs its number of calls, and the sum is the number of calls. When the work depends on the size, as in a scan, each level costs the calls times the size.
Use it when a function calls itself, and you want to know how long it runs. Signal words: a function that calls itself twice, how many calls, draw the tree.
Draw: one node for each call, with the size on it. Mark the leaves.
Count: the calls on each level, by running the function with a counter on small inputs, or by the rule: calls = 1 + the calls of the children.
Add up: for each level, the calls times the work of one call. Add the levels.
Compare: the calls with the different questions, and the depth with the limit.
def count_calls(n):
# [1] Base case: a call on 0 or 1 is a leaf, and it counts as one call.
if n < 2:
return 1
# [2] Recursive case: ask for the calls under n - 1 and under n - 2.
left = count_calls(n - 1)
right = count_calls(n - 2)
# [3] Total for this call: itself plus both subtrees.
return 1 + left + rightpublic int countCalls(int n) {
// [1] Base case: a call on 0 or 1 is a leaf, and it counts as one call.
if (n < 2) {
return 1;
}
// [2] Recursive case: ask for the calls under n - 1 and under n - 2.
int left = countCalls(n - 1);
int right = countCalls(n - 2);
// [3] Total for this call: itself plus both subtrees.
return 1 + left + right;
}int countCalls(int n) {
// [1] Base case: a call on 0 or 1 is a leaf, and it counts as one call.
if (n < 2) {
return 1;
}
// [2] Recursive case: ask for the calls under n - 1 and under n - 2.
int left = countCalls(n - 1);
int right = countCalls(n - 2);
// [3] Total for this call: itself plus both subtrees.
return 1 + left + right;
}function countCalls(n) {
// [1] Base case: a call on 0 or 1 is a leaf, and it counts as one call.
if (n < 2) {
return 1;
}
// [2] Recursive case: ask for the calls under n - 1 and under n - 2.
const left = countCalls(n - 1);
const right = countCalls(n - 2);
// [3] Total for this call: itself plus both subtrees.
return 1 + left + right;
}Rebuild the template: put its lines back in order. Loads in your browser.
Exercise · Find the bug: The leaf that counts as a branch. This function should return the number of calls weight(n) makes, but it is too large for n = 1 and every n above it. Which line is wrong?
def count_calls(n):
if n < 1:
return 1
left = count_calls(n - 1)
right = count_calls(n - 2)
return 1 + left + rightThe count follows the function: the base case, the two subtrees, and the total that includes the call itself.
The template is the function itself, with every answer replaced by a count. It follows the shape of the recursion, so it is easy to trust. The cost is the number of calls it makes, which is exactly the number it returns.
The work of a call is not always 1. A call that scans its input does size units of work. Then you add up the levels. Take a function that scans n items and then calls itself on the two halves.
def level_work(n):
# [1] Level 1 has one call, on all n items. The work of a level is its calls times the size of each.
calls = 1
size = n
total = 0
while size > 1:
# [2] A call on more than one item scans all its items, so the level adds calls * size.
total += calls * size
# [3] The next level has twice as many calls, each on half the items, rounded down.
calls *= 2
size //= 2
# [4] The last level holds calls on one item, and each is one unit of work.
return total + callspublic int levelWork(int n) {
// [1] Level 1 has one call, on all n items. The work of a level is its calls times the size of each.
int calls = 1;
int size = n;
int total = 0;
while (size > 1) {
// [2] A call on more than one item scans all its items, so the level adds calls * size.
total += calls * size;
// [3] The next level has twice as many calls, each on half the items, rounded down.
calls *= 2;
size /= 2;
}
// [4] The last level holds calls on one item, and each is one unit of work.
return total + calls;
}int levelWork(int n) {
// [1] Level 1 has one call, on all n items. The work of a level is its calls times the size of each.
int calls = 1;
int size = n;
int total = 0;
while (size > 1) {
// [2] A call on more than one item scans all its items, so the level adds calls * size.
total += calls * size;
// [3] The next level has twice as many calls, each on half the items, rounded down.
calls *= 2;
size /= 2;
}
// [4] The last level holds calls on one item, and each is one unit of work.
return total + calls;
}function levelWork(n) {
// [1] Level 1 has one call, on all n items. The work of a level is its calls times the size of each.
let calls = 1;
let size = n;
let total = 0;
while (size > 1) {
// [2] A call on more than one item scans all its items, so the level adds calls * size.
total += calls * size;
// [3] The next level has twice as many calls, each on half the items, rounded down.
calls *= 2;
size = Math.floor(size / 2);
}
// [4] The last level holds calls on one item, and each is one unit of work.
return total + calls;
}For n = 8 the levels are 1 call of 8, 2 calls of 4, 4 calls of 2 and 8 calls of 1. Each level does 8 units of work, and the total is 32. The loop adds the levels and makes no recursive call.
Exercise · Break it: Find the input where the levels do not add up. This function adds up the work of a scan and two halves, and assumes that every level costs n. Find an n where it gives the wrong total.
def level_work(n):
calls = 1
size = n
total = 0
while size > 1:
total += n
calls *= 2
size //= 2
return total + callsA scan of n items costs n, and the function then calls itself. The cost depends on how it calls itself. Each row below was measured by running the instrumented function for n = 1,024.
| Recursion | Calls | Total work |
|---|---|---|
One call on n - 1, after a scan of n |
1,024 | 524,800 |
One call on n // 2, after a scan of n |
11 | 2,047 |
Two calls on n // 2, after a scan of n |
2,047 | 11,264 |
The first row is a chain: the levels do 1,024, 1,023, 1,022 and so on, which is about n²/2. The second row halves the work at each level, so the total is about 2n. The third row does n units on every level, and there are 11 levels, so it is about n log n.
The same function body, a scan and calls on smaller inputs, gives three very different costs. The tree tells you which one you have.
A recursion on n - 1 makes a chain, with n levels and one call each. A recursion on n // 2 makes a short tree, with about log n levels. A recursion that calls itself twice on n - 1 and n - 2 makes a wide tree whose levels grow by about 1.6 each time.
So before you trust a recursion on a large input, draw its tree. Count the levels, the calls on each, and the work of one call.
weight(n) it is about 1.6 to the power n. For a scan and two halves it is about n log n.weight(n), and about log n for the halving.Real production data brings edge cases.
For n = 0 and n = 1, the call is a leaf: 1 call and a depth of 1. The count rule starts from these two values, so they must be right before any larger count is.
For n = 2, the call makes 2 leaf calls, so 3 calls in all. This is the smallest tree with an inner node, and it is the first place to check a formula.
When each call scans its input, the cost is not the number of calls. For n = 8 with two halves, the calls number 15, but the work is 32, not 15. Read the work of a call before you multiply.
For n = 70 the call count is 616,123,042,340,257. A 32-bit counter overflows at 2,147,483,647, so Java and C++ need a 64-bit integer. Python integers do not overflow.
This estimate says that a function with one recursive rule makes about as many calls as its input is large.
Counterexample: weight(10) makes 177 calls, and weight(20) makes 21,891. The input doubled, and the calls grew by a factor of 124. A function that calls itself twice grows by a factor on each step, not by an amount.
Count by running the instrumented function on a few inputs, and look at the ratios.
The root's work times the calls gives 120, but the levels do 8 units each, and the real total is 32.
This estimate multiplies the work of the first call, n, by the number of calls. It treats every call as if it were as large as the root.
Counterexample: a scan and two halves with n = 8 makes 15 calls. The estimate gives 8 × 15 = 120. The real work is 32, because the calls below the root work on smaller inputs.
Add up the levels: the calls on a level times the size of a call there.
This estimate reads the depth of the stack as the cost, because the stack is where the recursion lives.
Counterexample: a scan and two halves with n = 1,024 is 11 levels deep, and its work is 11,264. A reader who sees 11 frames and expects 11 units of work is off by a factor of about 1,000.
The depth tells you the memory on the stack. The cost is the sum over all the calls.
The tree of weight(40) has 331,160,281 nodes. If the function remembers each answer the first time, the second call on the same n returns at once, and the tree shrinks. Each different n does its work once.
With a cache, weight(40) makes 79 calls. The rule "cost is the number of nodes in the full tree" is the cost of the version with no cache. Once answers are remembered, count the different questions, and count a cache lookup as a call that costs almost nothing.
Your team lead brings four product changes. Each one changes the shape of the tree.
A feed sorts its posts by merging two sorted halves. Each call merges its range, which costs n, and then makes two calls on halves. This is the third row of the table, so the cost is about n log n (LeetCode 912: Sort an Array).
A recursive search looks at the middle and calls itself on one half. It does constant work in each call, and there are about log n calls, so the cost is about log n (LeetCode 704: Binary Search).
A rewards screen counts the ways to climb n steps by taking 1 or 2 steps at a time. The ways of n are the ways of n - 1 plus the ways of n - 2. This is the same tree as weight, and the same 15 calls for 5 steps (LeetCode 70: Climbing Stairs).
A function for the Fibonacci numbers has the same tree again. A table of n entries gives the value of fib(n). The last lesson of this module shows the same idea with a cache (LeetCode 509: Fibonacci Number).
Explain it back: write the idea in your own words and get feedback.
In two or three sentences, explain to a teammate how you find the cost of a recursion, and why the number of calls and the depth are different. The AI tutor checks your answer against the invariant and the key points of this lesson.
Here is how you could explain it in an interview, now that you have built it.
I draw the recursion tree: one node for each call, with the size on it. I count the calls on each level, by running a counter on small inputs, and by the rule that a call counts itself plus every call under it.
Then I multiply the calls on each level by the work of one call, and add the levels. When the work is constant, the cost is the number of calls.
The depth is the longest path, and it decides the stack. The calls decide the time, and they can be billions in a stack that is only 40 deep.
To find the cost of a recursion, I draw its tree. Each call is a node, and each call it makes is a child. The leaves answer at once, and the longest path is the depth of the stack.
Then I count the calls. I run the function with a counter on small inputs, and I look for the rule. For a function that calls itself on n minus 1 and n minus 2, the calls follow the same rule, so they grow by about 1.6 each step.
The cost is the calls times the work of one call. If the work is constant, the cost is the number of calls. If each call scans its input, I add up the levels.
The calls and the depth are different. A recursion can make billions of calls and have a stack that is only 40 deep. If the same call repeats, a cache turns the calls into the number of different questions.
Checkpoint · The tree
Q1/3 In a recursion tree, what is one node?
Answer: B
A node is a call, and an edge goes from a call to each call it makes. The number of nodes is the number of calls.
Q2/3 The function weight(n) makes two calls, weight(n - 1) and weight(n - 2), and a call on 0 or 1 answers at once. Which rule gives the number of calls?
Answer: C
A call counts itself, plus every call under each of its two children. Leaving out the 1 for the call itself gives the wrong count.
Q3/3 How many calls does weight(4) make?
Answer: C
weight(4) makes 1 + 5 + 3 = 9 calls, where 5 is the count for weight(3) and 3 is the count for weight(2).
Checkpoint · The cost
Q1/3 A function calls itself twice, and each call does 1 unit of work. The tree has 2,047 nodes. What is the cost?
Answer: C
With constant work, the cost is the number of calls. The depth tells the memory, not the time.
Q2/3 A call scans n items, then makes two calls on the halves. For n = 8 the tree has 15 calls. What is the total work, with 1 unit for a call on one item?
Answer: B
The levels do 8, 8, 8 and 8 units. The calls below the root work on smaller inputs, so the root's work cannot be multiplied by every call.
Q3/3 A function makes 331,160,281 calls for n = 40, and the stack is 40 deep. What does the depth tell you?
Answer: B
The stack holds one path of the tree. The time follows the number of calls, and the memory on the stack follows the depth.
Checkpoint · The shape
Q1/4 A call scans n items and calls itself once on n // 2. About how much work does it do in all?
Answer: B
Each level does half the work of the level above, so the work forms a sum that stops at about 2n.
Q2/4 A call scans n items and calls itself once on n - 1. About how much work does it do in all?
Answer: C
The levels form the sum n + (n - 1) + ... + 1, which is n(n + 1)/2. For n = 1,024 that is 524,800.
Q3/4 In weight(5), the call weight(1) appears five times in the tree. What does that tell you?
Answer: B
Only 6 different questions exist, from 0 to 5, and the tree asks 15. Repeated calls are the sign that remembering answers would help.
Q4/4 How do you find the number of calls of a new recursion with an unknown rule?
Answer: C
A counter on small inputs gives exact numbers quickly, and the rule can then be written and checked. Running the largest input may take longer than anyone can wait.
Ten questions on this lesson. Pass with 80% or more to be sure the idea has landed before the next lesson.
| Step | Problem | Product line | Level | What it practises |
|---|---|---|---|---|
| 1 | Calls made by a recursive total | Pay | Easy | Counting the leaves of a balanced tree, and reading the depth |
| 2 | Cost of the plain Fibonacci | Observe | Medium | Counting the calls of a tree that is not balanced, and its shallow stack |
| 3 | Cost of a halving recursion | Search | Medium | Adding up the work level by level, for one to three branches |
| 4 | Which recursion blows the stack | Chat | Medium | Telling the depth from the number of calls |
| 5 | Total work in a branching tree | Maps | Hard | Levels with uneven sizes, and a base case that costs more |
Review cards from this lesson.
Five cards from this lesson join your spaced-review deck. The first one comes back tomorrow.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Step through it.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.