Java Reference
In-Depth Information
class NodeData {
String word;
int freq;
public NodeData(String w) {
word = w;
freq = 0;
}
public void incrFreq() {
++freq;
}
public int compareTo(NodeData d) {
return this.word.compareTo(d.word);
}
public void visit() {
WordFrequencyBST.out.printf("%-15s %2d\n", word, freq);
}
} //end class NodeData
// class TreeNode goes here
// class BinaryTree (with findOrInsert added) goes here
Note that
in
and
out
are declared as
static
class variables. This is not necessary for
in
, which could have been
declared in
main
since it is used only there. However, the
visit
method of the
NodeData
class needs to know where to
send the output, so it needs access to
out
. We give it access by declaring
out
as a class variable.
Since
findOrInsert
requires a
NodeData
object as its argument, we must create a
NodeData
object from
word
before calling it in this statement:
TreeNode node = bst.findOrInsert(new NodeData(word));
An in-order traversal of the search tree yields the words in alphabetical order.
Suppose the file
wordFreq.in
contains the following data:
If you can trust yourself when all men doubt you;
If you can dream - and not make dreams your master;
If you can talk with crowds and keep your virtue;
If all men count with you, but none too much;
If neither foes nor loving friends can hurt you;
Search WWH ::
Custom Search