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;
}
}
java实现二叉查找树
最新推荐文章于 2024-09-06 06:25:05 发布