Computer Science 101

Data Abstraction

Gregory M. Kapfhammer

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

An Example

Recursive factorial

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

Let's try it!

Work with a team 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?

Try this later to develop understanding

Report back on the challenges you faced!

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?

How does this connect to algorithm analysis?

We will practice this in the assignments!

Schedule office hours to discuss further