二叉查找树

/**
 * 二叉查找树
 * T 节点元素类型
 */
public class BinarySearchTree<T extends Comparable<? super T>> {
    /*
     * 节点类
     */
	private static class BinaryNode<T> {
    	T element;
    	BinaryNode<T> left;
    	BinaryNode<T> right;
    	
		BinaryNode(T element) {
    		this(element, null, null);
    	}
    	BinaryNode(T element, BinaryNode<T> left, BinaryNode<T> right) {
    		this.element = element;
    		this.left = left;
    		this.right = right;
    	}
    	
    }
	/*
	 * 根
	 */
	private BinaryNode<T> root;
	/*
	 * 插入
	 */
	public void insert(T ele) {
		root = insert(ele, root);
	}
	public void remove(T ele) {
		root = remove(ele, root);
	}
	private BinaryNode<T> insert(T ele, BinaryNode<T> t) {
		if (t == null) {
			return new BinaryNode<T>(ele, null, null);
		}
		
		int result = ele.compareTo(t.element);
		if (result < 0) {
			t.left = insert(ele, t.left);
		} else if (result > 0) {
			t.right = insert(ele, t.right);
		} else {
			;
		}
		return t;
	}
	private BinaryNode<T> remove(T ele, BinaryNode<T> t) {
		if (t ==null ) {
			return t;
		}
		
		int result = ele.compareTo(t.element);
		if (result < 0) {
			return remove(ele, t.left);
		} else if (result > 0) {
			return remove(ele, t.right);
		} else if (t.left != null && t.right != null) {
			t.element = findMin(t.right).element;
			t.right = remove(t.element, t.right);
		}
		return t;
	}
	private BinaryNode<T> findMin(BinaryNode<T> t) {
		if (t != null) {
			while (t.left != null) {
				t = t.left;
			}
		}
	    return t;
	}
	/*
	 * 二叉查找树中是否包含此节点
	 */
	private boolean contains(T ele, BinaryNode<T> t) {
		if (t == null) {
			return false;
		}
		
		int result = ele.compareTo(t.element);
		
		if (result < 0) {
			return contains(ele, t.left);
		} else if (result > 0) {
			return contains(ele, t.right);
		}
		return true;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值