Recursion is well-suited for problems that have an intrinsic recursive structure. This also applies directly for many data structures, including linked lists (which we've seen before) and trees (which we introduce today). It will also turn out that for some operations, a recursive approach is natural while an iterative approach requires significant additional work.
By the way, I want to give a big thanks to Ashvin, who recorded walkthrough videos for this lecture.
1: Recursion on Linked Lists
1.1
As an initial example, let's consider the recursive structure implicit in a linked list as well as strategies for recursively processing the data stored in the list.
1.1 Exercise: Recursive List Functions
You're welcome to check your solution with this walkthrough video. |
2: Coding Recursive List Functions
2.1
Next, we'll take a quick look at coding up an implementation of a recursive list function. As usual, we primarily follow the conceptual base case and recurrence relation we've already worked out, but there are a few more details to consider once we get to the actual code.
2.1 Exercise: Coding
list_max()
Implement the You're welcome to check your solution with this walkthrough video. |
3: Recursion on Trees
3.1
Now, let's take a look at a new data structure, the binary tree. It turns out that binary trees underly many of the most efficient implementations of a variety of data structures, including sets and maps, which we'll talk about next time. Because trees are also a naturally recursive data structure, we'll apply recursion here as well.
3.1 Exercise: Recursive Tree Functions
You're welcome to check your solution with this walkthrough video. |
4: Coding Recursive Tree Functions
4.1
Let's take a look at a specific representation of trees in code, using a
4.1 Exercise: Coding
tree_height()
Implement the You're welcome to check your solution with this walkthrough video. |
5: Tree Traversals
To traverse and process each element in the tree, there are several possible orderings. (Contrast this to a linear data structure like a linked list where there is only one straightforward traversal.) Let's take a look at each: Here's a copy of the slide with all the traversals: |
6: Types of Recursion
6.1
6.2
6.3
Finally, let's take a look at several qualitatively different kinds of recursion we've seen so far. Generally, the distinguishing factors are the number and placement of the recursive calls.
6.1
Consider this function. What kind of recursion does it use?
6.2
Consider this function. What kind of recursion does it use?
6.3
Consider this function. What kind of recursion does it use?
|