复习5 平衡二叉树(AVL树)

平衡因子:左子树与右子树高度之差。

平衡因子的绝对值不超过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);
            }
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值