1066 Root of AVL Tree (25 分)

平衡二叉树包括:插入,获取高度,更新高度,左旋,右旋,新建结点,获取平衡因子,建立二叉树(只需插入所有结点)

#include<bits/stdc++.h>
using namespace std;
struct node{
    int v,height=-1;
    node *left,*right;
}*root;
node* newnode(int v){
    node* Node=new node;
    Node->v=v;
    Node->height=1;
    Node->left=Node->right=NULL;
    return Node;
}
int getheight(node* root){
    if(root==NULL)
        return 0;
    else return root->height;
}
void updateheight(node* root){
    root->height=max(getheight(root->left),getheight(root->right))+1;
}
int getBF(node* root){
    return getheight(root->left)-getheight(root->right);
}
void L(node* &root){
    node* temp=root->right;
    root->right=temp->left;
    temp->left=root;
    updateheight(root);
    updateheight(temp);
    root=temp;
}
void R(node* &root){
    node* temp=root->left;
    root->left=temp->right;
    temp->right=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->left,v);
        updateheight(root);
        if(getBF(root)==2){
            if(getBF(root->left)==1)            //LL型
                R(root);
            else if(getBF(root->left)==-1){          //LR型
                L(root->left);
                R(root);
            }
        }
    }
    else{
        insert(root->right,v);
        updateheight(root);
        if(getBF(root)==-2){        
            if(getBF(root->right)==-1)                     //RR
                L(root);
            else if(getBF(root->right)==1){              //RL
                R(root->right);
                L(root);
            }
        }
    }
}
int main(){
    int n,v;
    node* root=NULL;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        scanf("%d",&v);
        insert(root,v);
    }
    printf("%d\n",root->v);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值