Drawing the recursion tree to count calls

Video lessonComing soon

1 One call or two

countDigits from the call stack lesson calls itself once. Its calls form a line, one under the other, so counting them is easy.

Fibonacci Number is different. Each term is the sum of the two terms before it: 0, 1, 1, 2, 3, 5, 8, and so on. The term F(n) is F(n − 1) + F(n − 2), so a recursive fib calls itself twice.

The code is three lines long, yet at n = 50 it gets TLE. Its calls do not form a line. They branch, and every branch branches again. To see how many calls that makes, we draw them.

2 The plain recursive version

The base cases are F(0) = 0 and F(1) = 1, so for n ≤ 1 the function returns n. Every other call adds up two smaller calls.

It returns 5 for n = 5, 55 for n = 10 and 832040 for n = 30. The result is a 64-bit integer, because F(n) passes the int range at n = 47.

3 Drawing the tree level by level

The complexity lesson showed the calls of fib(4), 9 in all. Here we draw that tree ourselves. Each call is a node, and the first call, fib(4), goes at the top. Under every node we draw the calls it makes: fib(n − 1) on the left and fib(n − 2) on the right.

A call with n ≤ 1 makes no calls, so it is a leaf. We stop when every node at the bottom is a leaf. This drawing is the recursion tree.

LevelCalls on this levelCount
0fib(4)1
1fib(3), fib(2)2
2fib(2), fib(1), fib(1), fib(0)4
3fib(1), fib(0)2
120314120
The calls made by fib(4). Each node shows its n.

The counts add up to 9 calls. Levels 0 to 2 double: 1, 2, 4. Level 3 has only 2 calls, not 8, because three of the four calls on level 2 are leaves.

4 Counting: about 2ⁿ calls

Every call that is not a leaf makes two calls. So each level holds at most twice as many calls as the level above it: 1, 2, 4, 8, and so on.

The left edge of the tree goes fib(n), fib(n − 1), down to fib(1), so the tree has n levels. With n levels that each double, the calls add up to at most about 2ⁿ. Each call does one addition of its own, so the time is O(2ⁿ).

The right side of the tree drops by 2 at each level, so it is shorter. The real count stays below 2ⁿ, but it still multiplies as n grows. We added a counter that goes up by 1 at the start of fib and ran it:

nCalls
49
10177
20about 22,000
30about 2.7 million
40about 330 million
50about 4 × 10¹⁰

Each extra 10 multiplies the count by more than 100. At about 10⁸ steps a second, n = 40 already takes a few seconds. At n = 50 the code is far past the time limit, so it gets TLE.

n = 202.2 × 10⁴n = 302.7 × 10⁶n = 403.3 × 10⁸n = 504.1 × 10¹⁰about 1 second
Calls made by the plain fib, on a scale where each mark is ten times the last

The Fibonacci Number problem allows n up to 90, so this version does not pass there.

5 Depth is the height of the tree

The whole tree is never on the call stack at once. The program goes down the left side first: fib(4), fib(3), fib(2), fib(1). Then fib(1) returns and its frame pops. Only after that does fib(2) call fib(0).

So the stack holds one path from the top down to a leaf. The longest path is the left edge, with n calls. Its length is the height of the tree, and it is the recursion depth.

mainfib(4)fib(3)fib(2)fib(1)top →
The deepest point of fib(4): one path, 4 frames
  • Time follows the nodes. The tree has about 2ⁿ of them in the worst case.
  • Space follows the height. The stack holds at most n frames, so the space is O(n). At n = 50 that is 50 frames, which is tiny.

6 The same call, again and again

The tree for fib(4) has two nodes for fib(2). Each one makes the same calls below it, fib(1) and fib(0), and returns the same answer, 1.

120314120
fib(2) is calculated twice, with all its calls each time
CallTimes made
fib(4)1
fib(3)1
fib(2)2
fib(1)3
fib(0)2

The call fib(4) asks only 5 different questions, fib(0) to fib(4), but it makes 9 calls.

In bigger trees, whole branches repeat. The call fib(5) calculates fib(3) twice, with every call under it each time. At n = 50 there are 51 different questions and about 4 × 10¹⁰ calls, so almost every call repeats work done before.

Repeats like these are a strong hint. Saving each answer the first time and reusing it is memoisation, and it leads to dynamic programming later on the roadmap. For now, the skill is to spot the repeats in the drawing.

7 A line, and a short line

The shape of the tree comes from two things in the code: how many calls each call makes, and how fast the input shrinks.

  • One call on n − 1: a line. factorial(5) calls factorial(4), down to factorial(1). One call per level over n levels makes n calls. Time and depth are both O(n).
  • One call on n / 2: a short line. To raise x to the power n, we can calculate x to the power n / 2 once, then square it. The calls for n = 16 go 16, 8, 4, 2, 1. That is about log n levels, only about 30 at n = 10⁹.
12345
factorial(5): 5 calls
124816
power(x, 16): 5 calls
power(x, n)                    // n ≥ 1
    if n == 1
        return x
    half = power(x, n / 2)
    if n is even
        return half * half
    return half * half * x

The variable half matters. Writing power(x, n / 2) * power(x, n / 2) makes two calls again. The tree stays short, but every level doubles: 1, 2, 4, and so on.

1214121
power(x, 4) with the call written twice: 7 calls

Now power(x, 4) makes 7 calls instead of 3, and power(x, 10⁶) makes about a million. The halving saves nothing, and the time is O(n) again.

8 Reading the tree before submitting

When a function calls itself more than once, we draw the top three levels before we trust its speed. Two numbers decide the cost:

  • Branches. This is how many calls each call makes. It sets how fast the levels widen.
  • Height. This is how many levels it takes to reach the base case. A step of n − 1 gives about n levels, and a step of n / 2 gives about log n.

The number of calls is at most the branches raised to the power of the height. Two branches over n levels give 2ⁿ. One branch gives just the height. Two branches over log n levels give about n. Then we compare that count with the largest n in the constraints.

The other problems in this section, from the sum of the first n numbers to the digit sum, make one call each, so their trees are lines. Fibonacci Number is the first one that branches.

The habit to keep: for a recursion with more than one call, draw three levels, write how many calls each level holds, and look for a call that appears twice.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.