二叉查找树:

makeEmpty (): 使树为空;
isEmpty():判断是否为空
contains(T x):判断树中是否包含x
insert(T x):插入
remove(T x):删除
findMin();
findMax();
printTree():前序遍历。


public class BinarySearchTree <T extends Comparable<? super T>>{
	private class Node <T>{
		T element;
		Node<T> left;
		Node<T> right;
		public Node(T element) {
			super();
			this.element = element;
		}
		public Node(T element, Node<T> left, Node<T> right) {
			super();
			this.element = element;
			this.left = left;
			this.right = right;
		}
		
		
	}
	
	Node<T> root;
	public BinarySearchTree() {
		root=null;
	}
	public void makeEmpty() {
		root=null;
	}
	public boolean isEmpty() {
		return root==null;
	}
	public boolean contains(T x) {
		return contains(x,root);
		
	}
	public boolean contains(T x,Node<T> t) {
		if(t==null) {
			return false;
		}
		int compareResult=x.compareTo(t.element);
		if(compareResult<0) {
		return contains(x,t.left);
		}
		else if(compareResult>0) {
		return contains(x,t.right);
		}
		else {
		return true ;
		}
	}
	
	public void insert(T x) {
		root=insert(x,root);
	}
	public Node<T> insert(T x, Node<T> t) {
		if(t==null) {
			return new Node<T>(x,null,null);
		}
		int compareResult=x.compareTo(t.element);
		if(compareResult<0) {
			t.left=insert(x,t.left);
		}
		else if(compareResult>0) {
			t.right=insert(x,t.right);
		}
		else {
			;
		}
		
		return t;
		
	}
	public T findMin() {
		return findMin(root).element;
	}
	public Node<T> findMin(Node<T> t) {
		if(t==null)
		 return null;
		else if(t.left==null) {
			return t;
		}
		return  findMin(t.left);
	}
	public T findMax() {
		return findMax(root).element;
	}
	public Node<T> findMax(Node<T> t){
		if(t==null)
			return null;
		else
		{
			while(t.right!=null)
				t=t.right;
		}
		return t;
	}
	public void remove(T x) {
		root=remove(x,root);
	}
	public Node<T> remove(T x ,Node<T> t){
		if(t==null)
			return null;
		int compareResult=x.compareTo(t.element);
		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 min=findMin(t.right).element;
				t.element=findMin(t.right).element;
				t.right=remove(min,t.right);
			}
		else
			t=(t.left!=null)?t.left:t.right;
	
		return t;
	}
	public void printTree() {
		//前序遍历
		printTree(root);
	}
	public void printTree(Node<T> t) {
		if(t!=null) {
			System.out.println(t.element);
			printTree(t.left);
			printTree(t.right);
		}
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值