Professional Documents
Culture Documents
But you can't write the traversal recursively if you want to do this. Factoring the
traversal into iteration or forcing the use of a callback function are the only two
choices. The former is the lesser of the two evils, since you only have to do it
once and then can use many times in traversals.
Suppose that you need to pass some data to the recursive process. You might want
to keep a count of the number of nodes visited, or a set of parameters that
determine what to do at each node, or anything else. In order to do this, you have
to pass some data to every recursive call. This is a waste of time and space, unless
your compiler is much smarter than mine. Alternatively, you can use global
variables, but that's hardly a preferable solution.
Now, if you were to use an iterative solution instead, you could just have a single
set of local variables, and there is no need to pass anything recursively. This saves
the time and memory that would be used for passing these things in the recursive
calls.
Even worse, suppose, in the context of the binary search tree example, that
halfway through you discover that you need to change directions, move
backward. I don't even want to think about how to do that recursively. It's simply
impractical.
Avoiding recursive calls often avoids other kinds of overhead, such as the
system's unavoidable function call overhead. On some systems this can be
significant, so a transformation from recursion to iteration can improve both speed
and space requirements.