Computer Science 112:

Introduction to Computer Science II

Gregory M. Kapfhammer

flickr photo shared by Billboard Art Project under a Creative Commons ( BY-NC-ND ) license

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

See Figure 5.1 for a great diagram!

How does the JVM's stack support recursion?

File system traversal

"Natural" solution is recursive!

Disk usage calculation

Let's try it!

Work with a partner to implement Code Fragment 5.5

Save the method in a file called

Make sure to implement a main method

Try this method out on a small directory structure

How long did it take to traverse the directories?

Types of Recursion




Recursion can "run amok"

Incorrect recursion leads to inefficient algorithms

Be careful about how many recursive calls you create!

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?