二叉排序树java实现

二叉排序树:或者是一颗空树,或者具有下列性质的二叉树:左子树全小于它的根节点,右子树节点的值全部大于根节点的值,它的左右子树也分别为二叉排序树。

java实现:

package cn.stone.algorithm;

public class BinarySortTree{
	class BiTree{
		int data;
		BiTree lchild;
		BiTree rchild;
		
		public BiTree(int data,BiTree lchild,BiTree rchild){
			this.data=data;
			this.lchild=lchild;
			this.rchild=rchild;
		}
	}
	
	//查询
	public BiTree search(BiTree tree,int key){
		if((tree==null) || key==tree.data)
			return tree;
		else if(key<tree.data)
			return search(tree.lchild, key);
		else 
			return search(tree.rchild, key);
	}
	
	//增加
	BiTree p=null;
	public boolean getInsertNode(BiTree tree,int key,BiTree f){
		if(tree==null){
			p=f;
			return false;
		}else if(tree.data==key){
			p=tree;
			return false;
		}else if(tree.data>key){
			return getInsertNode(tree.lchild,key,tree);
		}else{	
			return getInsertNode(tree.rchild,key,tree);
		}
	}

	public boolean insert(BiTree tree,int key){
		if(!getInsertNode(tree,key,null)){
			BiTree node=new BiTree(key,null,null);
			if(p==null){
				tree=node;
			}else if(p.data<key){
				p.rchild=node;
			}else{
				p.lchild=node;
			}	
			return true;
		}
		return false;
	}
	
	//删除
	public boolean deleteBST(BiTree tree,int key){
		if(tree==null){
			return false;
		}else if(tree.data==key){
			return  delete(tree);
		}else if(tree.data>key){
			return deleteBST(tree.lchild,key);
		}else{	
			return deleteBST(tree.rchild,key);
		}
	}

	public boolean delete(BiTree tree){
		if(tree==null){
			return true;
		}else if(tree.lchild==null){
			tree=tree.lchild;
		}else if(tree.rchild==null){
			tree=tree.rchild;
		}else{
			BiTree p=tree;
			BiTree s=tree.lchild;
			while(s.rchild!=null){
				p=s;
				s=s.rchild;
			}
			tree.data=s.data;
			if(p!=tree){
				p.rchild=s.lchild;
			}else{
				p.lchild=s.lchild;
			}
		}
		return true;
	}
}

 

 

你可能感兴趣的:(二叉排序树)