平衡因子:左子树与右子树高度之差。
平衡因子的绝对值不超过1的二叉查找树。
1.树结构
struct node{
int v , height;
node *lChild , *rChild;
};
2.新建结点
node* newNode(int v){
node* Node = new node;
Node->v = v;
Node->height = 1;
Node->lChild = Node->rChild = NULL;
return Node;
}
3.获取结点高度
int getHeight(node* root){
if(root == NULL) return 0;
return root->height;
}
4.计算平衡因子
int getBalanceFactor(node* root){
return getHeight(root->lChild) - getHeight(root->rChild);
}
5.更新高度
void updateHeight(node* root){
root->height = max(getHeight(root->lChild) , getHeight(root->rChild)) + 1;
}
6.查找操作
等同于二叉搜索树
void search(node* root , int x){
if(root == NULL){
printf("Search Failed!\n");
return;
}
if(x == root->v){
printf("%d\n",root->v);
}else if(x < root->v){
search(root->lChild , x);
}else{
search(root->rChild , x);
}
}
7.AVL的插入操作
左旋:
void L(node* &root){
node* temp = root->rChild;
root->rChild = temp->lChild;
temp->lChild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
右旋:
void R(node* &root){
node* temp = root->lChild;
root->lChild = temp->rChild;
temp->rChild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
LL型 : BF(root) = 2,BF(root->lChild) = 1:对root进行右旋;
LR型 : BF(root) = 2,BF(root->lChild) = -1:对root->lChild进行左旋,再对root进行右旋;
RR型: BF(root) = -2,BF(root->rChild) = -1;对root进行左旋;
RL型: BF(root) = -2,BF(root->rChild) = 1;对root->rChild进行右旋,再对root进行左旋;
void insert(node* &root , int x){
if(root == NULL){
root = newNode(x);
return;
}
if(x < root->v){
insert(root->lChild , x);//插入左子树
updateHeight(root);
if(getBalanceFactor(root) == 2){
if(getBalanceFactor(root->lChild) == 1){//LL
R(root);
}else if(getBalanceFactor(root->lChild) == -1){//LR
L(root->lChild);
R(root);
}
}
}else{
insert(root->rChild , x);
updateHeight(root);
if(getBalanceFactor(root) == -2){
if(getBalanceFactor(root->rChild) == -1){//RR
L(root);
}else if(getBalanceFactor(root->rChild) == 1){//RL
R(root->lChild);
L(root);
}
}
}
}