平衡二叉树是一颗能够确保能在O(lgn)渐进时间界进行查找的树。我编写一个类来对平衡二叉树进行操作,包括,添加元素,删除元素,查找元素等操作。我建议:对于数据结构,如果都能够自己编写一遍,不仅能够摸清其中的奥妙,而且可以快速入手其他结构。
简单实现代码如下:可以直接复制使用,或者转为自己的jar文件
package Com.Tree;
import java.util.Comparator;
/**
* 注意:对于这个可变类,并未考虑线程安全的问题,也没有定义成不可变的类。主要体现平衡二叉树的实现方法。
* 在这个类中,最关键的地方是平衡例程,即balance方法,而balance方法需要调用几个辅助方法来帮助判断和旋转。
* 其余地方都与构建一颗二叉排序树ADT一样。
* 搞几个列子,balance()断点一步步走一遍,摸清楚他的执行过程。
* @author jane
*
* @param <T> 通用化处理,对于所有的可比较类(实现了comparable接口的类)都能进行排序。
*/
public class AVLSearchTree<T> {
// declare the comparator
private Comparator<? super T> cmp;
private int myCompare(T lhs, T rhs) {
if (cmp != null)
return cmp.compare(lhs, rhs);
else
return ((Comparable) lhs).compareTo(rhs);
}
// the class of Node
private static class AVLNode<T> {
T element;
AVLNode<T> left;
AVLNode<T> right;
int height;
AVLNode(T theElement) {
this(theElement, null, null);
}
AVLNode(T theElement, AVLNode<T> lt, AVLNode<T> rt) {
element = theElement;
left = lt;
right = rt;
height = 0;
}
}
// 封装一颗二叉平衡树,对于所有的实例域都要私有化。
private AVLNode<T> root;
// 外部访问接口。
public AVLSearchTree() {
root = null;
}
public AVLSearchTree(Comparator<? super T> c) // 从外部注入比较器,默认从小到大
{
root = null;
cmp = c;
}
public void makeEmpty() {
root = null;
}
public boolean isEmpty() {
return root == null;
}
// 是否包含
public boolean contains(T x) {
return contains(x, root);
}
// 找最小
public T findMin() {
if (isEmpty())
throw new NullPointerException();
return findMin(root).element;
}
public T findMax() {
if (isEmpty())
throw new NullPointerException();
return findMax(root).element;
}
// 插入
public void insert(T x) {
root = insert(x, root);
}
// 删除
public void remove(T x) {
root = remove(x, root);
}
/**
* 三种遍历二叉树的方式,
*
* @param type:参数0为先序遍历,参数1为中序遍历,2为后序遍历。默认为先序遍历
*/
public void printTree(int type)