目录
实现AVL算法
AVL算法中的左旋、右旋、双旋定义在此不多做赘述,不会的请自行百度,下面我就该算法本身的实现做出展示。
首先,由于多了一个平衡因子,那么自然在节点中就必须增加一个新的域,使得我们可以跟踪以该结点为根的子树的高度,以此来计算平衡因子。结点修改如下
class AVLNode{
String key;
int height;
AVLNode left,right;
}
得到二叉树结点的高度:
private int getHeight(AVLNode node){
return (node==null)?-1:node.height;
}
在每次插入结点实现后对树的高度进行更新操作:
private void fixHeight(AVLNode node){
if(node!=null){
node.height=Math.max(getHeight(node.left),getHeight(node.right))+1;
}
}
左旋操作:
private AVLNode rorateLeft(AVLNode node){
AVLNode child=node.right;
node.right=child.left;
child.left=node;
fixHeight(node);
fixHeight(child);
return child;
}
右旋操作:
private AVLNode rorateRight(AVLNode node){
AVLNode child=node.left;
node.left=child.right;
child.right=node;
fixHeight(node);
fixHeight(child);
return child;
}
双旋操作:
private AVLNode fixLeftImbalance(AVLNode node){
AVLNode child=node.left;
if(getHeight(child.right)>getHeight(child.left)){
node.left=rorateLeft(child);
}
return rorateRight(node);
}
private AVLNode fixRightImbalance(AVLNode node){
AVLNode child=node.right;
if(getHeight(child.left)>getHeight(child.right)){
node.right=roateRight(child)l
}
return rorateLeft(node);
}
以上算法都是为了优化插入算法的,接下来给出插入算法的实现:
private AVLNode insertNode(AVLNode node,String key){
if(node==null){
node=new AVLNode();
node.key=key;
node.left=node.right=null;
node.height=0;
}else{
int cmp=key.compareTo(node.key);
if(cmp<0){
node.left=insertNode(node.left,key);
}else if(cmp>0){
node.right=insertNode(node.right,key);
}
int bf=getHeight(node.right)-getHeight(node.left);//平衡因子
if(bf==-2){
node=fixLeftImbalance(node);
}else if(bf==2){
node=fixRightImbalance(node);
}
}
return node;
}