Recursion Trees
Recursion Trees
Recursion Trees
2
Recursion Trees
3
Fibonacci Tree Problem
Fibonacci - Recursion Tree
// POST: return value is the n-th
// Fibonacci number F(n)
ifmp::integer fib (const unsigned int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fib(n-1) + fib(n-2); // n > 1
}
fib(4):
5
Fibonacci - Recursion Tree
// POST: return value is the n-th
// Fibonacci number F(n)
ifmp::integer fib (const unsigned int n) {
if (n == 0) return 0;
if (n == 1) return 1;
return fib(n-1) + fib(n-2); // n > 1
}
fib(4):
1 1 0
1 0
6
Fibonacci - Recursion Tree
fib(4):
1 1 0
1 0
7
Fibonacci - Recursion Tree
fib(4):
1 1 0
1 0
8
Fibonacci - Recursion Tree
fib(4):
1 1 0
1 0
9
Fibonacci - Recursion Tree
fib(4):
Many more
function calls!
1 1 0
1 0
10
Fibonacci - Recursion Tree
n fib(n)
fib(4): 5
Many5more
10 55
function calls!
20 6’765
40 102’334’155
80 23’416’728’348’467’685
1 1 0
1 0
11
Fibonacci - Recursion Tree
n fib(n)
fib(4): 5
Many5more
10 55
function calls!
20 6’765
40 102’334’155
80 23’416’728’348’467’685
Requires
unbelievably 1 1 0
many recursive
1 0
calls!
12
The Problem
13
The Problem
1 1 0
1 0
14
The Problem
1 1 0
1 0
15
The Problem
16
The Problem
17
The Problem
18
The Problem
20 > 6’765 39
40 > 102’334’155 79
19
The Problem
20 > 6’765 39
40 > 102’334’155 79
Mindblowing
difference!
20
The Problem
21