Lesson 1 · Unit 02
Two calls, one tree
Why branching recursion grows so fast
What you practise
- The Fibonacci call tree, counting calls, exponential growth
Try a question from this lesson
Pick one
In the sequence 0, 1, 1, 2, 3, 5 each number is the sum of the two before it. What does this print?
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(6))function fib(n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(6));function fib(n: number): number {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(6));Correct answer
8
Why
fib(0) is 0 and fib(1) is 1, the two base cases. From there: 1, 2, 3, 5, 8, so fib(6) is fib(5) + fib(4) = 5 + 3 = 8. This function makes two recursive calls where a simple countdown makes one.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Two calls make a tree
One recursive call per call gives a chain. Two give a tree: every call that is not a base case splits into two more.
This is everything fib(4) sets off. The leaves are the base cases, and the same small calls appear again and again.
fib(4)
/ \
fib(3) fib(2)
/ \ / \
fib(2) fib(1) fib(1) fib(0)
/ \
fib(1) fib(0) fib(4)
/ \
fib(3) fib(2)
/ \ / \
fib(2) fib(1) fib(1) fib(0)
/ \
fib(1) fib(0) fib(4)
/ \
fib(3) fib(2)
/ \ / \
fib(2) fib(1) fib(1) fib(0)
/ \
fib(1) fib(0)9 more exercises in the app
- 2× type the answer
- 3× multiple choice
- 1× true or false
- 1× fill the blanks
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.