next up previous index
Next: The abstract SearchTree class Up: Java implementation Previous: Empty trees and node   Index

Discussion

There is a fair amount to be taken in here. Let's begin with something simple. The abstract SearchTree class promises an isEmpty method. This remains an abstract method in the SearchTree class because it will be implemented differently in the two sub-classes, just as area was implemented differently for shapes. We see that EmptyTree implements this by always returning true, and NodeTree by always returning false.

The second point to note is that SearchTree provides a static empty method, which returns an empty tree. This can be used in an application to declare and initialise a SearchTree variable such as

SearchTree t = SearchTree.empty();
The empty method just calls the EmptyTree constructor which itself has an empty body. In fact, it is not necessary to include this constructor in the EmptyTree class explicitly. The only purpose of including it is to give it protected status. The EmptyTree class ought not to be instantiated directly by a client of the SearchTree class. We want it to be instantiated only through a call to the public SearchTree.empty method. In fact, neither of the two subclasses EmptyTree or NodeTree is intended to be instantiated directly by the client, hence the protected status for the NodeTree constructor as well.

Turning now to the NodeTree class, we see have it has three private instance variables; data which must be a Comparable, and a left and right sub-tree, each of which is itself a SearchTree. The data item must implement the Comparable interface, because our insertion and searching routines will make use of the order property (S) at the beginning. Note also that the left and right sub-trees are declared to be of type SearchTree rather than NodeTree. This allows them to be instances of either NodeTree or EmptyTree in a particular case.

The NodeTree constructor takes a single item or type Comparable as parameter, and assigns this to the data instance variable. It assigns an empty tree to each of the left and right sub-trees. This constructor is only for our own implementation purposes, and although other variants are possible this is sufficient. Note that as written, we assign a new empty tree to each of left and right whenever the constructor is called. This is somewhat inefficient in both space and time. It is really only necessary to have a single empty tree. In the on-line code you will find the following:

private static SearchTree empty = empty();

protected NodeTree(Comparable item) {
    data = item;
    left = empty;
    right = empty;
}
Here we have defined a single static constant empty for private use, and this constant is used in the NodeTree constructor.


next up previous index
Next: The abstract SearchTree class Up: Java implementation Previous: Empty trees and node   Index
Peter Williams 2005-06-07