Java Reference
In-Depth Information
The function will read data from the input stream associated with the Scanner , in . It uses the following
definition of NodeData :
class NodeData {
String word;
public NodeData(String w) {
word = w;
}
} //end class NodeData
We will call buildTree from the following constructor:
public BinaryTree(Scanner in) {
root = buildTree(in);
}
Suppose a user class has its tree data stored in the file btree.in . It can create a binary tree, bt , with the
following code:
Scanner in = new Scanner(new FileReader("btree.in"));
BinaryTree bt = new BinaryTree(in);
Having built the tree, we should want to check that it has been built properly. One way to do that is to perform
traversals. Suppose we want to print the nodes of bt in pre-order. It would be nice to be able to use a statement such
as this:
bt.preOrder();
To do so, we would need to write an instance method preOrder in the BinaryTree class. The method is shown
in the following listing of the class. It also includes the methods inOrder and postOrder . We also retain the no-arg
constructor so the user can start with an empty binary tree, if desired.
The BinaryTree class
import java.util.*;
public class BinaryTree {
TreeNode root;
public BinaryTree() {
root = null;
}
public BinaryTree(Scanner in) {
root = buildTree(in);
}
public static TreeNode buildTree(Scanner in) {
String str = in.next();
if (str.equals("@")) return null;
TreeNode p = new TreeNode(new NodeData(str));
p.left = buildTree(in);
p.right = buildTree(in);
Search WWH ::




Custom Search