Cover Data Structures and Algorithms with Object-Oriented Design Patterns in Java
next up previous contents index

Depth-First Traversal

Program gif defines the depthFirstTraversal method of the AbstractTree class. The traversal method takes one argument--any object that implements the PrePostVisitor interface defined in Program gif.

   program15450
Program: AbstractTree class depthFirstTraversal method.

A PrePostVisitor is a visitor with four methods, preVisit, inVisit, postVisit, and isDone. During a depth-first traversal the preVisit and postVisit methods are each called once for every node in the tree. (The inVisit method is provided for binary trees and is discussed in Section gif).

   program15468
Program: PrePostVisitor interface.

The depth-first traversal method first calls the preVisit method with the object in the root node. Then, it calls recursively the depthFirstTraversal method for each subtree of the given node. After all the subtrees have been visited, the postVisit method is called. Assuming that the isEmpty, getKey, and getSubtree methods all run in constant time, the total running time of the depthFirstTraversal method is

displaymath62780

where n is the number of nodes in the tree, tex2html_wrap_inline62784 is the running time of preVisit, and tex2html_wrap_inline62786 is the running time of tex2html_wrap_inline62788.


next up previous contents index

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