Logo Data Structures and Algorithms with Object-Oriented Design Patterns in C++
next up previous contents index

Depth-First Traversal

Program gif gives the definition of the DepthFirstTraversal member function of the Tree class. The traversal routine takes one argument--a reference to an instance of the PrePostVisitor class defined in Program gif. A PrePostVisitor is a visitor with two additional member functions, PreVisit and PostVisit. During a depth-first traversal each function is called once for every node in the tree.

   program16196
Program: Tree Class Traversal Member Function Definitions

The depth-first traversal routine first calls the PreVisit function with the object in the root node. Then, it calls recursively the DepthFirstTraversal function for each subtree of the given node. After all the subtrees have been visited, the PostVisit function is called. Assuming that the IsEmpty, Key and Subtree member functions all run in constant time, the total running time of the DepthFirstTraversal routine is

displaymath63902

where n is the number of nodes in the tree, tex2html_wrap_inline63906 is the running time of PreVisit, and tex2html_wrap_inline63908 is the running time of tex2html_wrap_inline63910.


next up previous contents index

Bruno Copyright © 1997 by Bruno R. Preiss, P.Eng. All rights reserved.