CS 200: Deep Recursion

In regular recursion, we would recurse over the top level elements of a list, string, or tuple.

There are other recursive data structures that have multiple levels, for example, trees.

A tree, like the UNIX file system, has a root node. Each node can contain terminals nodes, called "leaves", or other nodes or branches. These nodes are called children. The main node is the parent. For example, in a UNIX directory, .. refers to the parent directory and . refers to the child directory. If a UNIX program spawns a process, the new process is the child and the originating process is the parent. (In C, you use the fork command to create a child process.)

The recursive function must process each node and all the children nodes.

Our first example procedure is maptree(proc, tree) which creates a copy of the given tree, with each leaf node replaced by proc(leafnode)

The base case is when a node is empty, an integer, or some other leaf node.

The recursive case is a list, in which the function is called recursively on each element of the list, and returns a copy of the list with appropriate modifications.

The functions in this notebook are from recursion.py

We will redefine maptree using a list comprehension

Here is a nested list comprehension version of maptree.

Oops. This does not quite work. I invite you to fix it

We can also use the map function to traverse trees.

Yet another attempt. This time I combine map with recursion.

We will now look at a deep recursive function that does not return a copy of the tree. It simply returns the number of leaf nodes in the tree.

End of Deep Recursion notebook.