There are many good answers here, but I made this diagram that helps to better explain the result of the function. The only values that will ever be returned are 1 or 0 (your example returns 1 for n <2, but should return n instead).
This means that each recursive call will ultimately return either 0 or 1. Ultimately, they are "cached" on the stack and "wrap" to the original call and added together.
So, if you were to draw the same diagram for each "n" value, you could manually find the answer.
This diagram roughly illustrates how each function returns for fib (5).

This shows the control flow, that is, the execution order for functions. Remember that code always runs on the left-> right and on the top-> bottom. Therefore, whenever a new function is called, it pauses, and then the next call occurs.
Below is the actual control flow based on your original message. Note that the basic condition is if (n <= 0) {return 0} else if (n <= 2) {return 1;} to simplify:
1. fib(5) { return fib(4) + fib(3); 2. fib(4) { return fib(3) + fib(2); 3. fib(3) { return fib(2) + fib(1); 4. fib(2) { A= return 1; }; 5. fib(1) { B= return 1; }; C= return 2; // (1 + 1) }; 6. fib(2) { D= return 1; }; E= return 3; // (2 + 1) }; 7. fib(3) { return fib(2) + fib(1); 8. fib(2) { F= return 1; }; 9. fib(1) { G= return 1; }; H= return 2; // (1 + 1) }; I= return 5; // (3 + 2) };
Jeff Callahan Nov 30 '15 at 21:14 2015-11-30 21:14
source share