Java Reference
In-Depth Information
Although the DefaultMutableTreeNode implementation of TreeNode allows you to
traverse a tree via the getNextNode() and getPreviousNode() methods, these methods are
extremely inefficient and should be avoided. Instead, use one of the special methods of
DefaultMutableTreeNode to produce one Enumeration of all of a node's children. Before looking
at the specific methods, review Figure 17-18, which shows a simple tree to traverse.
Figure 17-18. Sample tree for traversal
Figure 17-18 will help you understand the three special methods of DefaultMutableTreeNode .
These methods allow you to traverse a tree in any one of three ways, each public and returning
an Enumeration :
preOrderEnumeration() : Returns an Enumeration of nodes, like the printDescendants()
method. The first node in the Enumeration is the node itself. The next node is that node's
first child, then it's the first child of that first child, and so on. Once a leaf node with no
children is found, the next child of its parent is put in the Enumeration and its children
are added to the list accordingly until no nodes are left. Starting at the root for the tree in
Figure 17-18, this would result in an Enumeration of nodes in the following order: root ,
New York , Mets , Yankees , Rangers , Football , Giants , Jets , Bills , Boston , Red Sox , Celtics ,
Bruins , Denver , Rockies , Avalanche , Broncos .
depthFirstEnumeration() and postOrderEnumeration() : Return an Enumeration that has
practically the opposite behavior of preOrderEnumeration() . Instead of including the
current node first and then adding the children, these methods add the children first and
then add the current node to the Enumeration . For the tree in Figure 17-18, this results in
an Enumeration of nodes in the following order: Mets , Yankees , Rangers , Giants , Jets ,
Bills , Football , New York , Red Sox , Celtics , Bruins , Boston , Rockies , Avalanche , Broncos ,
Denver , root .
breadthFirstEnumeration() : Returns an Enumeration of nodes added by level. For the
tree in Figure 17-18, the Enumeration would be in the following order: root , New York ,
Boston , Denver , Mets , Yankees , Rangers , Football , Red Sox , Celtics , Bruins , Rockies ,
Avalanche , Broncos , Giants , Jets , Bills .
 
Search WWH ::




Custom Search