Java Reference
In-Depth Information
TreeNode(NodeData d) {
data = d;
left = right = null;
}
}
To keep our options open, we have defined
TreeNode
in terms of a general data type that we call
NodeData
. Any
program that wants to use
TreeNode
must provide its own definition of
NodeData
.
For example, if the data at a node is an integer,
NodeData
could be defined as follows:
class NodeData {
int num;
public NodeData(int n) {
num = n;
}
} //end class NodeData
A similar definition can be used if the data is a character. But we are not restricted to single-field data. Any
number of fields can be used. Later, we will write a program to do a frequency count of words in a passage. Each node
will contain a word and its frequency count. For that program,
NodeData
will contain the following, among other
things:
class NodeData {
String word;
int freq;
public NodeData(String w) {
word = w;
freq = 0;
}
} //end class NodeData
In addition to the nodes of the tree, we will need to know the root of the tree. Keep in mind that once we know the
root, we have access to all the nodes in the tree via the left and right pointers. Thus, a binary tree is defined solely by its
root. We will develop a
BinaryTree
class to work with binary trees. The only instance variable will be
root
. The class
will start as follows:
class BinaryTree {
TreeNode root; // the only field in this class
BinaryTree() {
root = null;
}
//methods in the class
} //end class BinaryTree
The constructor is not really necessary since Java will set
root
to
null
when a
BinaryTree
object is created.
However, we include it to emphasize that, in an empty binary tree,
root
is
null
.
Search WWH ::
Custom Search