二叉查找树的插入,删除,查找

二叉查找树的添加,删除,查找算法:

import java.util.Scanner;

public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> {

	BiNode root;
	class BiNode<AnyType>{
		AnyType data;
		BiNode left;
		BiNode right;
		public BiNode(AnyType data){
			this.data=data;
		}
        public BiNode(AnyType data,BiNode left,BiNode right){
			this.data=data;
			this.left=left;
			this.right=right;
		}
	}

	//添加
	public void insert(AnyType x){
		root=insert(x,root);
	}
	public BiNode insert(AnyType x,BiNode t){
	   if(t==null)
		   return new BiNode(x,null,null);
	   int compareResult=x.compareTo((AnyType)t.data); 
	   if(compareResult>0)
		   t.right=insert(x,t.right);
	   if(compareResult<0)
	       t.left=insert(x,t.left);
	   else;
	   return t;
		   
	}
	//查找
	public boolean contains(AnyType x){
		return contains(x,root);
	}
	public boolean contains(AnyType x,BiNode t){
		if(t==null)
			return false;
		int compareResult=x.compareTo((AnyType)t.data);
		if(compareResult>0)
			   return contains(x,t.right);
		if(compareResult<0)
			    return contains(x,t.left);
		else 
			return true;
	}
	//找最大和最小
	public AnyType findMin(){
	   	
		return (AnyType) findMin(root).data;
			
	}
	public BiNode findMin(BiNode t){
		if(t==null)
			return null;
		else if(t.left==null)
			return t;
		else
			return findMin(t.left);
	}
	public AnyType findMax(){		   	
		return (AnyType) findMax(root).data;
		}
	public BiNode findMax(BiNode t){
		if(t==null)
			return null;
		else if(t.left==null)
			return t;
		else
			return findMax(t.left);
		}
	//删除
	public void remove(AnyType x){
		root=remove(x,root); 
	}
	public BiNode remove(AnyType x,BiNode t){
		if(t==null)
			return t;
		int compareResult=x.compareTo((AnyType)t.data);
		if(compareResult<0)
			t.left=remove(x,t.left);
		else if(compareResult>0)
			t.right=remove(x,t.right);
		    else if(t.left!=null&&t.right!=null){
			t.data=findMin(t.right).data;
		    t.right=remove((AnyType)t.data,t.right);
		    }
		    else
				t=(t.left!=null)?t.left:t.right;

		return t;	
	}
	//中序遍历
	public void inOrder(){
		inOrder(root);
	}
	public void inOrder(BiNode t){
		if(t!=null){
			inOrder(t.left);
			System.out.print(t.data+"    ");
			inOrder(t.right);
		}
		
	}
		
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		BinarySearchTree<Integer> bsh=new BinarySearchTree<Integer>();
		for(int i=0;i<6;i++){                                 //输入六个数,个数可改变
			int numble=sc.nextInt();
			bsh.insert(numble);
		}
		bsh.inOrder();
	}

}

    原文作者:IT专业户
    原文地址: https://www.cnblogs.com/oversea201405/p/3752255.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞