CS 23001 CS II Data Structures and Abstraction
CS 23001 CS II: Data Structures and Abstraction Recursion Xiang Lian Department of Computer Science Kent State University Email: xlian@kent. edu Homepage: http: //www. cs. kent. edu/~xlian/ 1
Objectives • Recursion • Factorial & Fibonacci Examples • Conversion from Recursion to Iterative Version • Tower of Hanoi 2
Recursion • A recursive function is a function that calls itself – The number of recursive calling should not be infinite 3
Recall: Stack 4
Recursive Function • Base case – Must have • Recursive step 5
Factorial of n • Factorial of n – n! = n * (n-1) * … * 2 * 1 • Input: integer n • Output: n! 6
Pseudo Code of Factorial int Factorial(int n) { if (n<=1) // base case return 1; else // recursive step return n*Factorial (n-1); } 7
Fibonacci Number • • 1, 1, 2, 3, 5, 8, 13, 21, … F 1 = 1 base case F 2 = 1 F 3 = F 1 + F 2 = 2 F 4 = F 2 + F 3 = 3 … recursive step Fn = Fn-1 + Fn-2 8
Fibonacci Problem • Input: integer n • Output: Fn 9
Examples • Factorial • Fibonacci 10
Conversion from Recursion to Iterative Version int Factorial (int n) { if (n<=1) // base case return 1; else // recursive step return n*Factorial (n-1); } 11
int Factorial (int n) { Stack <int> sta; bool flag = true; // flag for recursive call int elem, rlt; if (n<2) return 1; sta. push(n); sta. push(n-1); // first function call while (!sta. contain. One. Elem()) { elem = sta. top(); if (flag) { if (elem <= 1) {flag = false; sta. pop(); } else sta. push(elem-1); } else { rlt = sta. pop(); elem = sta. pop(); sta. push(elem * rlt); } } return sta. pop(); } Iterative Version 12
Tower of Hanoi 13
Tower of Hanoi • Game Demo – https: //www. mathsisfun. com/games/towerofhanoi. html 14
15
- Slides: 15