next up previous index
Next: Discussion Up: Java implementation Previous: Abstract classes   Index

Empty trees and node trees

With this background in mind we can now implement the idea expressed in the defining property (B) above. This says that a binary tree is either an empty tree or consists of data together with a pair of binary trees. Let us call the latter sort of tree a NodeTree. Then a binary search tree, which we now call a SearchTree, is either an EmptyTree or a NodeTree, just as a Shape was either a Circle or a Square.

Our Java class definitions will now look as follows. The beginning of the abstract SearchTree class will be

public abstract class SearchTree {

    public static SearchTree empty() {
        return new EmptyTree();
    }

    public abstract boolean isEmpty();

    .... more methods
}
This will have two extensions, one for EmptyTree and one for NodeTree. The EmptyTree extension will begin
class EmptyTree extends SearchTree {

    protected EmptyTree() {}
  
    public boolean isEmpty() {
        return true;
    }

    .... more methods
}
The NodeTree extension will begin
class NodeTree extends SearchTree {

    private Comparable data;
    private SearchTree left;
    private SearchTree right;
  
    protected NodeTree(Comparable item) {
        data = item;
        left = empty();
        right = empty();
    }
  
    public boolean isEmpty() {
        return false;
    }

    .... more methods
}


Peter Williams 2005-06-07