public class BinarySortTree <V>{
class BinarySortNode<V>{
public int key;
public V value;
public BinarySortNode<V> lChild;
public BinarySortNode<V> rChild;
public BinarySortNode(){
key = 0;
value = null;
lChild = null;
rChild = null;
}
public BinarySortNode(int k,V v){
key = k;
value = v;
lChild = null;
rChild = null;
}
public boolean isLeaf(){//是否为叶子节点
if (lChild==null && rChild==null){
return true;
}else {
return false;
}
}
}
public BinarySortNode<V> root;
public BinarySortTree(int k,V v){
root = new BinarySortNode<V>(k,v);
}
BinarySortNode<V> search(BinarySortNode<V> node,int key){//在root所指的二叉树中查找某关键字等于key的元素,若查找成功则返回该节点,否则返回null
if (node==null||key==node.key) return node;
else if (key<node.key) return search(node.lChild,key);
else return search(node.rChild,key);
}
public void getParent(BinarySortNode<V> p,BinarySortNode<V> parent){//查找节点p的双亲节点
if (parent==null) return;
if (parent.isLeaf()){//parent不能是叶子节点
p=null;
return;
}
if (parent.lChild==p || parent.rChild==p) return;//找到双亲,结束查找
else {
getParent(p,parent.lChild);//搜索左右子树
getParent(p,parent.rChild);
}
}
public boolean inser(int k,V v){//插入数据元素
BinarySortNode<V> p,pre;//p指向当前节点,pre指向p的父节点
boolean isSearched = false;//假定二叉树不存在<k,v>的数据元素
p = root;//刚开始p和pre都指向根节点
pre = root;
while (p!=null && k!=p.key){//搜索二叉树并标记插入位置
pre = p;
if (k<p.key) p = p.lChild;//在左右子树中查找
else p = p.rChild;
}
if (p!=null && k==p.key){
isSearched = false;//要插入的节点存在,不需要插入
return false;
}
else {
p = new BinarySortNode(k,v);
if (k<pre.key){
pre.lChild = p;
}else {
pre.rChild = p;
}
return true;
}
}
public boolean delete(BinarySortNode<V> p){
if (p==null) return false;
BinarySortNode<V> f = this.root;
getParent(p,f);//从根节点开始查找p的双亲,查找成功时f指向双亲结点
if (f==null) return false;
if (p.isLeaf()){//如果p是叶子节点
if (f.lChild==p) f.lChild =null;
if (f.rChild==p) f.rChild =null;
return true;
} else if (p.lChild!=null && p.rChild==null) {//如果p只有左子树
f.lChild = p.lChild;
return true;
}else if (p.lChild==null && p.rChild!=null){//如果p只有右子树
f.rChild = p.rChild;
return true;
}else {//p既有左又有右
if (f.lChild==p)//令p的左子树接替p
f.lChild = p.lChild;
else if (f.rChild==p) {
f.rChild = p.lChild;
}
BinarySortNode<V> t = p.rChild;
if (t.rChild!=null){//搜素p的左子树的最右下节点t
while (t.rChild!=null) t=t.rChild;
}
t.rChild = p.rChild;//令p的右子树成为t的右子树
return true;
}
}
}