I'm trying to clarify the order in which recursive calls get executed. I read through this link: Dynamic programming and Divide and conquer
The function was written like this:
int Fibonacci(int n) {
if (n <= 1) return n;
return Fibonacci(n - 1) + Fibonacci(n - 2);
}
The call order was described like this:
If you trace out the calls done to compute Fibonacci(4), we get
Fibonacci(4) calls Fibonacci(3) and Fibonacci(2)
Fibonacci(3) calls Fibonacci(2) and Fibonacci(1)
Fibonacci(2) calls Fibonacci(1) and Fibonacci(0)
Fibonacci(2) (the other one) calls Fibonacci(1) and Fibonacci(0)
Fibonacci(1) terminates.
Fibonacci(1) terminates.
Fibonacci(1) terminates.
Fibonacci(0) terminates.
Fibonacci(0) terminates.
This brings up two questions:
(1) For this code:
return Fibonacci(n - 1) + Fibonacci(n - 2);
Does the call on the left-hand-side of the + sign always get called before the call on the right hand side? I think we get some sort of depth-first chain of function calls, where the straight line call Fib(5)...Fib(4)...Fib(3)...Fib(2)...Fib(1) gets called in a row before anything else gets called in the tree branching process. Is that true?
(2) I'm not understanding why the branches terminate in this order: Fibonacci(1) terminates. Fibonacci(1) terminates. Fibonacci(1) terminates. Fibonacci(0) terminates. Fibonacci(0) terminates.
I thought the termination order would simply be the leaf-order from left-to-right at the bottom of the tree: 1 0 1 1 0
Thanks for any insights on this.