初识:平衡二叉树知识点
下面就是代码了。
struct node {
int v, height; //v 权值 height 当前子树高度
node *lchild, *rchild;
};
node* newNode(int v){
node* Node = new node;
Node->v = v;
Node->height = 1;
Node->lchild = Node->rchild = NULL;
return Node;
}
获取以root为根节点的子树的当前height
int getHeight(node *root){
if(root == NULL) return 0;
return root->height;
}
计算root的平衡因子
int getBalanceFactor(node* root){
//左子树减右子树高度
return getHeight(root->lchild) - getHeight(root->rchild);
}
为什不直接记录结点的平衡因子,而是记录高度?因为没有办法通过当前结点的子树的平衡因子计算得到该结点的平衡因子,而需要借助子树的高度间接求得, 结点root所在的子树的height 等于其左子树height 与右子树height 的较大值 + 1,
void updateHeight(node* root){
root->height = max( getHeight(root->lchild), getHeight(root->rchild) ) + 1;
}
平衡二叉树的基本操作
1)查找(简单一匹,给二叉排序树一样)
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);
}
}
2)插入和删除才是重点。先来 插入。
两种旋转
4种情况 LL RR 找 A,B结点 从刚插入结点位置向上,找到第一个root平衡因子绝对值为2的为A结点,与A孩子中平衡因子为1的为B结点(和刚插入结点一侧)。然后 B 变成 根结点,A变B得右子树
LR RL 关键就在找 A,B,C结点 还是先找A,找到第一个root平衡因子绝对值为2的为A结点,与A孩子中平衡因子为1的为B结点(和刚插入结点一侧),B的孩子中和刚插入结点一侧的为C结点。 然后调平衡,C变根节点,A, B根据 是RL(A变C的左,B变C的右) 还是LR型(A变C的右,B变C的左)进行改变。
(1)左旋
void L(node* &root){
node* temp = root->rchild;
root->rchild = temp->lchild;
temp->lchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
2 ) 右旋
void R(node* &root){
node* temp = root->lchild;
root->lchild = temp->rchild;
temp->rchild = root;
updateHeight(root);
updateHeight(temp);
root = temp;
}
插入调平
void insert(node* &root, int v){
if(root == NULL){
root = newNode(v);
return;
}
if( v < root->v ){
insert(root->rchild, v);
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, v);
updateHeight(root);
if(getBalanceFactor(root) == 2){
if(getBalanceFactor(root->rchild) == 1){ //RR型
L(root);
}else if(getBalanceFactor(root->rchild) == -1){ //RL型
R(root->rchild);
L(root);
}
}
}
}
AVL树的建立
node* Create (int data[], int n){
node* root = NULL;
for(int i = 0; i < n; i++){
insert(root, data[i]);
}
return root;
}