next up previous index
Next: add Up: EmptyTree and NodeTree implementations Previous: nrNodes   Index

contains

The contains method is again simple for EmptyTree. Nothing is present in the empty tree, so we have
public boolean contains(Comparable item) {
    return false;
}
In the NodeTree class, however, we have to implement the algorithm described at the beginning of these notes, which we do recursively.
public boolean contains(Comparable item) {
    int compare = item.compareTo(data);
    if (compare < 0) {
        return left.contains(item);
    } else if (compare > 0) {
        return right.contains(item);
    } else {
        return true;
    }
}
This returns true if the third case (compare == 0) occurs before we arrive at an EmptyTree. Otherwise the method returns false when it is eventually called for an empty tree. Note that, if the item is not found, eventually either left or right is an EmptyTree and therefore either left.contains or right.contains is the contains method of the EmptyTree class.



Peter Williams 2005-06-07