next up previous contents
Next: Binary trees (of integer Up: Binary search trees Previous: The size of a   Contents

Recursive algorithms

Sometimes students have difficulties with recursion. A source of confusion is that it appears that ``the algorithm calls itself''. This way of putting things, although suggestive, can be misleading the first time we encounter recursion.

The algorithm itself is a passive entity, which actually can't do anything at all, let alone call itself. What happens is that a processor (which can be a machine or a person) executes the algorithm. So what goes on when a processor executes a recursive algorithm such as the above? An easy way of understanding this is to imagine that whenever a recursive call is encountered, new processors are given the task with a copy of the same algorithm.

For example, suppose that I (the first processor in this task) want to compute the size of a tree $ t$ using the above recursive algorithm. Then, according to the above algorithm, I first check whether it is empty. If it is, I return zero and finish my computation. If not, then my tree $ t$ has to have left and right subtrees $ l$ and $ r$ and some value $ v$ at its root node; that is, it is of the form $ t={\tt MkTree}(v,l,r)$. In this case, I ask two students, say John and Mary, to execute the same algorithm, but for the trees $ l$ and $ r$. When they finish, say with results $ m$ and $ n$ respectively, I compute $ m+n+1$, because my tree has a root node in addition to the left and right subtrees. John and Mary themselves may delegate executions of the same algorithm, with further subtrees, to other people. Thus, the algorithm is not calling itself, what happens is that there are many people running copies of the same algorithm.

In our example, in order to make things understandable, we assume that each person executes a single copy of the algorithm. However, the same processor, with some difficulty, can impersonate several processors, in such a way that a recursive algorithm can be executed by a single processor achieving the same result as the above execution involving many processors. This is achieved via the use of a stack that keeps track of the various positions of the same algorithm that are currently being executed -- but this knowledge is not needed for our purposes.


next up previous contents
Next: Binary trees (of integer Up: Binary search trees Previous: The size of a   Contents
Martin Escardo 2005-01-11