学习中写的,所以注释少,结构杂乱,难免有不足之处,望批评改正。如有需要笔者解释的地方,请将问题发到笔者邮箱(lixding@163.com)。
public class AVLTreeClass <AnyType extends Comparable<AnyType>>{
//节点类
public static class AVLNode<AnyType>{
AnyType data;//数据
AVLNode<AnyType> leftNode;//左子树
AVLNode<AnyType> rightNode;//右子树
int height=0;//高度
public AVLNode(AnyType data){
this.data=data;
this.leftNode=null;
this.rightNode=null;
}
public AVLNode(AVLNode<AnyType> left,AVLNode<AnyType> right,AnyType data){
this.data=data;
this.leftNode=left;
this.rightNode=right;
}
public AVLNode() {}
//获取树的高度
public int getHeight(AVLNode<AnyType> node){
return node==null?-1:node.height;//空树返回-1
}
}
private AVLNode<AnyType> root=null;//定义根节点
public AVLTreeClass(){
}
public void insert(AnyType x){
root=insert(x,root);
}
public AnyType getRoot(){
return root.data;
}
private AVLNode<AnyType> insert(AnyType x,AVLNode<AnyType> node){
if(node==null){
return new AVLNode<AnyType>(x);
}
int compareConsult=x.compareTo(node.data);
if(compareConsult<0){
node.leftNode=insert(x,node.leftNode);
if(node.getHeight(node.leftNode)-node.getHeight(node.rightNode)==2){
if(x.compareTo(node.data)<0) {
node=rotateWithLeftChild(node);
}
else{
node=doubleWithLeftChild(node);
}
}
}
else if(compareConsult>0){
node.rightNode=insert(x,node.rightNode);
if(node.getHeight(node.rightNode)-node.getHeight(node.leftNode)==2){
if(x.compareTo(node.data)>0) {
node=rotateWithRightChild(node);
}
else{
node=doubleWithRightChild(node);
}
}
}
else
;//do nothing
node.height=Math.max(node.getHeight(node.leftNode), node.getHeight(node.rightNode))+1;
return node;
}
private AVLNode<AnyType> doubleWithRightChild(AVLNode<AnyType> node) {
node.rightNode=rotateWithLeftChild(node.rightNode);
return rotateWithRightChild(node);
}
private AVLNode<AnyType> doubleWithLeftChild(AVLNode<AnyType> node) {
node.leftNode=rotateWithRightChild(node.leftNode);
return rotateWithLeftChild(node);
}
private AVLNode<AnyType> rotateWithRightChild(AVLNode<AnyType> node) {
AVLNode<AnyType> node2=node.rightNode;
node.rightNode=node2.leftNode;
node2.leftNode=node;
node.height=Math.max(node.getHeight(node.leftNode), node.getHeight(node.rightNode))+1;
node2.height=Math.max(node2.getHeight(node2.leftNode),node.height)+1;
return node2;
}
private AVLNode<AnyType> rotateWithLeftChild(AVLNode<AnyType> node) {
AVLNode<AnyType> node2=node.leftNode;
node.leftNode=node2.rightNode;
node2.rightNode=node;
node.height=Math.max(node.getHeight(node.leftNode), node.getHeight(node.rightNode))+1;
node2.height=Math.max(node2.getHeight(node2.leftNode), node.height)+1;
return node2;
}
}