class BST<E extends Comparable<E>> {
private BSTNode<E> root;
private int nodecount;
BST() {
root = null;
nodecount = 0;
}
public void clear() {
root = null;
nodecount = 0;
}
public void insert(E e) {
root = inserthelp(root, e);
nodecount++;
}
private BSTNode<E> inserthelp(BSTNode<E> rt, E e) {
if (rt == null)
return new BSTNode<E>(e);
if (rt.value().compareTo(e) >= 0)
rt.setLeft(inserthelp(rt.left(), e));
else
rt.setRight(inserthelp(rt.right(), e));
return rt;
}
public E remove(E key) {
E temp = findhelp(root, key);
if (temp != null) {
root = removehelp(root, key);
nodecount--;
}
return temp;
}
private BSTNode getmax(BSTNode rt) {
if (rt.right() == null)
return rt;
return getmax(rt.right());
}
private BSTNode<E> deletemax( BSTNode<E> rt){
if( rt.right() == null)
return rt.left();
rt.setRight(deletemax(rt.right()));
return rt;
}
Remove a node with key value k
@return
private BSTNode<E> removehelp(BSTNode<E> rt, E key) {
if (rt == null) return null;
if (rt.value().compareTo(key) > 0)
rt.setLeft(removehelp(rt.left(), key));
else if (rt.value().compareTo(key) < 0)
rt.setRight(removehelp(rt.right(), key));
else {
if (rt.left() == null)
return rt.right();
else if (rt.right() == null)
return rt.left();
else {
BSTNode<E> temp = getmax(rt.left());
rt.setValue(temp.value());
rt.setLeft(deletemax(rt.right()));
}
}
return rt;
}
public E find(E key) {
return findhelp(root, key);
}
private E findhelp(BSTNode<E> rt, E key) {
if (rt == null)
return null;
if (rt.value().compareTo(key) > 0)
return findhelp(rt.left(), key);
if (rt.value().compareTo(key) == 0)
return rt.value();
else
return findhelp(rt.right(), key);
}
public int size() { return nodecount; }
}