SLIDE 1 CS171 Introduction to Computer Science II
2/28/2012 1
Recursion
Li Xiong
SLIDE 2
What we have learned so far
Basic data structure
Arrays Linked list
Abstract data types Abstract data types
Stacks Queues
SLIDE 3
Linked List
A Linked List is a sequence of nodes chained together. Each node, element, or link contains a data item, and a reference to next node
SLIDE 4
Stacks and Queues
Can be implemented by both (resizing) arrays and linked list
SLIDE 5
Today
Quiz on stacks, queues, linked list Recursion
SLIDE 6
Recursion
Recursion concept Examples
Factorial Fibonacci GCD GCD Recursive graph Htree
Next lecture
Divide and conquer Binary search Tower of Hanoi Cost analysis of recursive algorithms
SLIDE 8
What is recursion?
SLIDE 9
SLIDE 10
Factorial
N! = N*(N-1)*(N-2)*…..* 2 * 1
SLIDE 11
Recursive Method
A method that calls itself (direct recursion)
SLIDE 12
Recursive Method
A method that calls itself (direct recursion) Every recursive method must have a base case that is not recursive
SLIDE 13 Better version of recursion definition
Recursion
- n. If you still don't get
it, see Recursion.
SLIDE 14
Recursion
A method calls itself
Calls a “clone” of itself to solve a smaller problem Buck Passing
Must have a base case Must have a base case
The buck stops here! (does not call the method)
SLIDE 15
Example: Fibonacci Numbers
Recursive formula:
= −+ − = =
0, 1, 1, 2, 3, 5, 8, 13, …..
SLIDE 16
Fibonacci Numbers: Java Code
SLIDE 17
SLIDE 18
SLIDE 19
SLIDE 20
SLIDE 21
Visual Recursion
SLIDE 22 Fractals
2/28/2012 22
SLIDE 23
SLIDE 24
SLIDE 25
SLIDE 26
SLIDE 27
Recursion
Recursive method Examples
Factorial Fibonacci GCD GCD Recursive graph Htree
Next lecture
Divide and conquer Binary search Tower of Hanoi Cost analysis of recursive algorithms