二叉排序树

整个二叉排序树的定义:

 

 

二叉排序树节点的定义:

public class BinaryNode<AnyType>{

   BinaryNode(AnyType e){
              this(e,null,null);
   }
         BinaryNode(AnyType e, BinaryNode l,BinaryNode r){
              element = e;
              left = l;
              right = r;  
         } 

          AnyType element;
          BinaryNode left;
          BinaryNode right;
         
}   

 

二叉查找树的contains操作:

public boolean contains(AnyType x;BinaryNode<AnyType> t ){
        if(t == null ) return false;
   
        if(x<t.element){
              contains(x,t.left)
        }   else if(x>t.element){
               contains(x,t.right)
         }  else {
               return true;
         }
}    

 

二叉查找树的findMax 和findMin操作,一个recursion一个非recursion

 

public BinaryNode<AnyType> findMax(AnyType x,BinaryNode<AnyType> t){
         if(t!=null){
          while(t.right !=null)  t = t.right; }
           return t; 

}
public BinaryNode<AnyType> findMin(AnyType x,BinaryNode<AnyType> t){
           if(t == null) return null;
           if(t.left == null) return t;
           return findMin(t.left);



}

 

二叉排序树的插入:

public void insert(AnyType x,BinaryNode<AnyType> t){
        if(t==null) return new BinaryNode(x,null,null);
        if(x<t.val) 
            t.left=insert(x,t.left);
        else if(x>t.val) 
            t.right=insert(x,t.right);
        else //已经有了,就不加了
        return t;

}

 

 

二叉排序树的删

public BinaryBode<AnyType> remove(AnyType x,BinaryNode<AnyType> t){
        if(t == null) return t;
        if(x<t.element){
            t.left = remove(x,t.left);
        }else if(x>t.element){
            t.right = remove(x,t.right);
        }else{ 
               if(t.left != null && t.right != null){
                    t.element = findMin(t.right).element;
                    t.right = remove(t.element,t.right);
                }
                else{
                    t= (t.left==null)? t.right:t.left;
                }
      }
return t; }

 

除:

 

posted @ 2019-04-27 22:38  星之眷属  阅读(175)  评论(0编辑  收藏  举报