1. 程式人生 > >java實現二叉查詢樹

java實現二叉查詢樹

package ustc.zyy.ArrayList;

/**
 * @author zhang yin ye 
 * @date 2014 6 17
 * 
 */

import java.util.DuplicateFormatFlagsException;

public class BinarySearchTree<E extends Comparable<? super E>> {
	// 樹根
	private BinaryNode<E> root;

	public BinarySearchTree() {
		root = null;
	}

	// 使得樹為空
	public void makeEmpty() {
		root = null;
	}

	// 判斷樹是不是空的
	public boolean isEmpty() {
		return root == null;
	}

	// 獲得指定節點的元素值
	private E elementAt(BinaryNode<E> t) {
		return t == null ? null : t.element;
	}

	// 刪除從跟節點開始的最小節點
	public void removeMin() {
		root = removeMin(root);
	}

	// 上面呼叫了這個受保護的方法 傳遞一個BinaryNode<E>型別的節點
	protected BinaryNode<E> removeMin(BinaryNode<E> t) {
		if (t == null)
			throw new ArrayIndexOutOfBoundsException();
		else if (t.left != null) {
			// 遞迴呼叫 直到沒有左子節點為止
			t.left = removeMin(t.left);
			return t;
		} else
			// 要是沒有左節點 直接返回右節點
			return t.right;

	}

	public void insert(E e) {
		root = insert(e, root);
	}

	// 遞迴的插入元素x
	protected BinaryNode<E> insert(E x, BinaryNode<E> t) {
		if (t == null)
			// 要是根節點為空 則以新插入的節點為根
			t = new BinaryNode<E>(x);
		else if (x.compareTo(t.element) < 0)
			t.left = insert(x, t.left);
		else if (x.compareTo(t.element) > 0)
			t.right = insert(x, t.right);
		else
			// 相等就丟擲異常
			throw new DuplicateFormatFlagsException(x.toString());
		return t;
	}

	public E findMin() {
		return elementAt(findMin(root));
	}

	protected BinaryNode<E> findMin(BinaryNode<E> t) {
		if (t != null)
			while (t.left != null)
				t = t.left;
		return t;
	}

	public E findMax() {
		return elementAt(findMax(root));
	}

	protected BinaryNode<E> findMax(BinaryNode<E> t) {
		if (t != null)
			while (t.right != null)
				t = t.right;
		return t;
	}

	public E find(E x) {
		return elementAt(find(x, root));
	}

	protected BinaryNode<E> find(E x, BinaryNode<E> t) {
		while (t != null) {
			if (x.compareTo(t.element) < 0)
				t = t.left;
			else if (x.compareTo(t.element) > 0)
				t = t.right;
			else
				return t;
		}
		return null;
	}

	public void remove(E x) {
		root = remove(x, root);
	}

	//
	protected BinaryNode<E> remove(E x, BinaryNode<E> t) {
		if (t == null)
			// throw new ArithmeticException();
			System.out.print("根節點為空節點");
		if (x.compareTo(t.element) < 0)
			t.left = remove(x, t.left);
		else if (x.compareTo(t.element) > 0)
			t.right = remove(x, t.right);
		else if (t.left != null && t.right != null) {
			t.element = findMin(t.right).element;
			t.right = removeMin(t.right);
		} else {
			t = (t.left != null) ? t.left : t.right;
		}
		return t;

	}

}