1 Data Structures CSCI 132, Spring 2016 Notes 16 Tail Recursion
2 Tail Recursion When the recursive function call is the last thing that occurs in the recursive function, this is called a Tail Recursion. In a tail recursion, there are no pending operations. Any tail recursion can be written as an iteration (a loop).
3 Factorial Revisited int Fact (int n) { if (n <= 0) { return 1; } else { return n * Fact (n - 1); } Is this a tail recursion? No. Can we write this as a tail recursion? Yes! Keep track of the answer in a parameter that gets passed on.
4 Tail Recursion Factorial int factTail (int num, int ans) { if (num <= 0) { return ans; } else { return factTail(num - 1, num*ans); } } int factIter (int n) {//Helper function to initialize ans return factTail(n, 1); }
5 Execution of FactTail numansnum*ansFunction Calls 414Fact(4, 1): Fact(3, 4): Fact(2, 12): Fact(1, 24): (returned)Fact(0, 24):24
6 Writing factTail as an iteration int factWhile (int n) { }
7 Writing factTail as an iteration int factWhile (int n) { int num = n; int ans = 1; while (num > 0) { ans = ans * num; num = num - 1; } return ans; }
8 Recall Fibonacci
9 Fibonacci in C++ code int Fib( int n ) { if (n < 2) { return n; } else { return Fib(n-1) + Fib(n -2); }
10 Recursive Fibonacci repeats computations
11 Fibonacci as a Tail Recursion nifib(i-1)fib(i)fib(i_next) (fib(i) + fib(i-1)) Pass values as parameters of the recursive function: n, i, fibIminus1, fibI (we will work on this in lab).
12 The Tower of Hanoi Setup: A stack of rings in order of largest to smallest is on one of three pegs (largest on the bottom, smallest on the top). Object: Move stack from one peg to another peg following these rules: 1) Cannot put a ring on top of a smaller ring. 2) Can only move 1 ring at a time.
13 Tower of Hanoi Demo A BC
14 Tower of Hanoi Demo A BC
15 Tower of Hanoi Demo A BC
16 Tower of Hanoi Demo A BC
17 Tower of Hanoi Demo A BC
18 Tower of Hanoi Demo A BC
19 Tower of Hanoi Demo A BC
20 Tower of Hanoi Demo A BC
21 Tower of Hanoi Demo A BC
22 Tower of Hanoi Demo A BC
23 Tower of Hanoi Demo A BC
24 Tower of Hanoi Demo A BC
25 Tower of Hanoi Demo A BC
26 Tower of Hanoi Demo A BC
27 Tower of Hanoi Demo A BC
28 Tower of Hanoi Demo A BC
29 Strategy for Tower of Hanoi 1) Move top (n-1) rings from origin to spare (following all the rules). 2) Move bottom ring from origin to destination 3) Move top (n-1) rings from spare to destination (following all the rules).
30 Implementing Tower of Hanoi void hanoi(int n, char start, char end, char spare) { if (n < = 0) { //do nothing } else { hanoi(n-1, start, spare, end); cout << "Move disk " << n << "from " << start << " to " << end << endl; hanoi(n-1, spare, end, start); } } //Outputs sequence of moves to solve tower of hanoi!
31 Invocation Tree for hanoi nodes How long will it take to move a tower 100 rings high?