public boolean isEmpty() {
return root == null;
}
public boolean contains(AnyType x){
return contains(x,root);
}
public AnyType findMin(){
if (isEmpty()) throw new BufferUnderflowException();
return findMin(root).element;
}
public AnyType findMax(){
if (isEmpty()) throw new BufferUnderflowException();
return findMax(root).element;
}
public void insert(AnyType x){
root = insert(x, root);
}
public void remove(AnyType x){
root = remove(x,root);
}
1.4、比较函数
如果有比较器,就使用比较器,否则要求对象实现了Comparable接口;
private int myCompare(AnyType lhs, AnyType rhs) {
if (cmp != null) {
return cmp.compare(lhs, rhs);
} else {
return lhs.compareTo(rhs);
}
}
1.5、contains 函数
本质就是一个树的遍历;
private boolean contains(AnyType x, BinaryNode t) {
if (t == null) {
return false;
}
int compareResult = myCompare(x, t.element);
if (compareResult < 0) {
return contains(x, t.left);
} else if (compareResult > 0) {
return contains(x, t.right);
} else {
return true;
}
}
1.6、findMin
因为二叉搜索树的性质,最小值一定是树的最左节点,要注意树为空的情况。
/**
-
Internal method to find the smallest item in a subtree
-
@param t the node that roots the subtree
-
@return node containi