Computer Science 112:

Introduction to Computer Science II

Gregory M. Kapfhammer

flickr photo by by physician1977 shared under a CC Public Domain Dedication (CC0)

Color Scheme

Key Concept

Corresponding Diagram

In-Class Discussion

In-Class Activity

Details in the Textbook

Recursion achieves repetition


Method makes one or more calls to itself

Process stops when a base case is reached

Visualized with a call tree or a program stack

Data structure relies on smaller instances of itself

Any questions about the definitions?

Elegant (yet, sometimes confusing!) approach

Previous Recursive Examples

Recursive factorial and recursive GCD

Can you find the recursive call?

Can you find the base case?

How do these programs work?

Review recursive factorial in greater detail

Trace of a recursive method call

See Figure 5.1 for a great diagram!

How does the JVM's stack support recursion?

Binary search

File system traversal

"Natural" solution is recursive!

Disk usage calculation

Types of Recursion




See Section 5.3 for more details

Recursion can "run amok"

Incorrect recursion leads to inefficient algorithms

Be careful about how many recursive calls you create!

Computing Fibonacci numbers

See Page 217 for an Example

Why is this recursion run amok?

Maximum Recursive Depth

Details vary depending on JVM implementation

Possible to store about 1000 simultaneous calls

What happens when you exceed the limit?

Be careful to avoid StackOverflow exceptions!

Any questions about recursion?