AVL树的定义自己百度去,这里给出自己用java的一个实现。
package test;
/**
* @时间 2014-3-30
* @version 0.1
* @encode UTF-8
* @功能
* 1、AVL树的生成
* 2、插入元素
* 3、删除元素
* 4、查找某一元素
* @notice 树元素需实现Comparor接口
* @see 《数据结构与算法分析》第4章4.4节
* */
public class AVLTree >{
public AVLTree(){
this(null);
}
public AVLTree(T t){
data=t;
parent=null;
leftChild=null;
rightChild=null;
height=t==null?-1:0;
}
public int getHeight(){
return updateHeight();
}
public AVLTree getRoot(){
if(data==null)
return null;
AVLTreeroot=this;
while(root.parent!=null)
root=root.parent;
return root;
}
public AVLTreegetLeftChild(){
return leftChild;
}
public AVLTreegetRightChild(){
return rightChild;
}
public AVLTreegetParent(){
return parent;
}
public boolean isEmpty(){
return data==null;
}
/**从当前节点所在的AVL树中插入新元素;若参数是空值则不予插入
* @return 新的根节点
* */
public AVLTree insert(T t){
if(t==null)
return this;
//特殊情形:当前是空节点
if(data==null){
data=t;
updateHeight();
return this;
}
AVLTreeroot=getRoot();//根节点
return root.rootInsert(t);
}
/**从当前节点所在的AVL树中删除节点
* @return 新的根节点
*/
public AVLTree delete(T t){
AVLTreeroot=getRoot();
return root.rootDelete(t);
}
/**从当前节点所在的AVL树中查找元素所在节点*/
public AVLTree find(T t){
AVLTreeroot=getRoot();
return root.rootFind(t);
}
/**打印树*/
public void display(){
//空节点、叶子节点不打印
if(data==null||(parent!=null&&leftChild==null&am