We use a simple approach to removing an item from an EmptyTree
public SearchTree remove(Comparable item) {
return this;
}
The item is not present, so there is nothing to do. But we have to
return a SearchTree, so we just return this.
The problem of removing an item from a NodeTree is quite delicate. The problem is, of course, to maintain the ordering property (S). This means rearranging the tree, and there is no unique solution to this. In general it is desirable to maintain a good balance to the tree. Here we shall just be satisfied to remove the item and maintain the ordering property.
Suppose that we wish to remove the item 21 from the original binary search tree
The code for removing an item from a NodeTree is shown in Figure 8.2
private Comparable findMin() {
if (left.isEmpty()) {
return data;
} else {
return ((NodeTree) left).findMin();
}
}
private SearchTree removeMin() {
if (left.isEmpty()) {
return right;
} else {
left = ((NodeTree) left).removeMin();
return this;
}
}
public SearchTree remove(Comparable item) {
int compare = item.compareTo(data);
if (compare == 0 && right.isEmpty()) {
return left;
} else {
if (compare < 0) {
left = left.remove(item);
} else if (compare > 0) {
right = right.remove(item);
} else {
data = ((NodeTree) right).findMin();
right = ((NodeTree) right).removeMin();
}
return this;
}
}
|
Note also the type coercion in, for example,
data = ((NodeTree) right).findMin();The reason is that the methods findMin and removeMin are only needed for non-empty trees, and we only define them in the NodeTree class. If you were to write
data = right.findMin();you would get an error message
findMin() not found in class SearchTreeNote also that we only force this type coercion after we have checked that the tree in question is not empty.