Java Reference
In-Depth Information
return p;
} //end buildTree
public void preOrder() {
preOrderTraversal(root);
}
public void preOrderTraversal(TreeNode node) {
if (node!= null) {
node.data.visit();
preOrderTraversal(node.left);
preOrderTraversal(node.right);
}
} //end preOrderTraversal
public void inOrder() {
inOrderTraversal(root);
}
public void inOrderTraversal(TreeNode node) {
if (node!= null) {
inOrderTraversal(node.left);
node.data.visit();
inOrderTraversal(node.right);
}
} //end inOrderTraversal
public void postOrder() {
postOrderTraversal(root);
}
public void postOrderTraversal(TreeNode node) {
if (node!= null) {
postOrderTraversal(node.left);
postOrderTraversal(node.right);
node.data.visit();
}
} //end postOrderTraversal
} //end class BinaryTree
The traversals all use the statement node.data.visit(); . Since node.data is a NodeData object, the NodeData
class should contain the method visit . In this example, we just print the value at the node, so we write visit as
follows:
public void visit() {
System.out.printf("%s ", word);
}
We now write Program P8.1, which builds a binary tree and prints the nodes in pre-order, in-order, and post-
order. As usual, we can declare the class BinaryTree as public and store it in its own file, BinaryTree.java . We can
also declare the class TreeNode as public and store it in its own file, TeeeNode.java . However, if you prefer to have the
Search WWH ::




Custom Search