Java Reference
In-Depth Information
5
6 // post: constructs a leaf node with given data
7 public SearchTreeNode(E data) {
8 this (data, null, null);
9 }
10
11 // post: constructs a node with the given data and links
12 public SearchTreeNode(E data, SearchTreeNode<E> left,
13 SearchTreeNode<E> right) {
14 this .data = data;
15 this .left = left;
16 this .right = right;
17 }
18 }
So what about the SearchTree class? You can get a pretty close approximation of
the code for this class by replacing all occurrences of int with E and replacing all
occurrences of IntTreeNode with SearchTreeNode<E> . But you have to make a
few adjustments. First, the private add method looks like this after the substitution:
private SearchTreeNode<E> add(SearchTreeNode<E> root, E value) {
if (root == null) {
root = new SearchTreeNode<E>(value);
} else if (value <= root.data) {
root.left = add(root.left, value);
} else {
root.right = add(root.right, value);
}
return root;
}
The problem here is that you have to call the compareTo method rather than using
the <= operator. You'll replace the line of code:
} else if (value <= root.data) {
with:
} else if (value.compareTo(root.data) <= 0) {
You have to make a similar change in the private contains method. You have to
use calls on the compareTo method rather than simple comparisons. Because the
method has more than one comparison, in this case it makes sense to call compareTo
once and store it in a local variable:
private boolean contains(SearchTreeNode<E> root, E value) {
if (root == null) {
 
Search WWH ::




Custom Search