The add method does something substantial for empty trees.
public SearchTree add(Comparable item) {
return new NodeTree(item);
}
This constructs a new NodeTree with the item in its
data field, with empty left and right
subtrees, and returns it. In fact every insertion is ultimately done
in this way. For the NodeTree class we have
public SearchTree add(Comparable item) {
int compare = item.compareTo(data);
if (compare < 0) {
left = left.add(item);
} else if (compare > 0) {
right = right.add(item);
}
return this;
}
Note that ultimately this is returned, i.e. the reference is
unchanged, but that the left or right subtrees may
have changed. Assuming the item is not already present in
the tree, eventually left or right will be empty and
the add method called will be from the EmptyTree
class. If the item is already present, nothing happens and
the original tree is returned. (Other approaches are possible, but
this is the simplest.)