PAT A1066 Root of AVL Tree (25point(s))

AC Code:

#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
    int data,height;//data为结点数据域,height为高度
    node *left,*right;//分别为左右孩子结点指针
};
node* creatnode(int x){//创建新结点
    node *root=new node;
    root->data=x;//把x赋给数据域
    root->height=1;//高度初始化为1
    root->left=root->right=NULL;//左右孩子指针初始化为NULL
    return root;
}
int getheight(node *root){//获取高度
    if(root==NULL) return 0;//要注意空结点的高度,防止段错误
    return root->height;
}
void updataheight(node *root){//更新高度
    root->height=max(getheight(root->left),getheight(root->right))+1;
    //本结点高度等于左右子树高度的最大值加1
}
int balancefactor(node* root){//计算平衡因子
  return getheight(root->left)-getheight(root->right);
}
void R(node* &root){//右旋
    node* temp=root->left;
    root->left=temp->right;
    temp->right=root;
    updataheight(root);
    updataheight(temp);
    root=temp;
}
void L(node* &root){//左旋
    node* temp=root->right;
    root->right=temp->left;
    temp->left=root;
    updataheight(root);//先更新旋转后位于下面的结点高度
    updataheight(temp);//再更新旋转后位于上面的结点高度
    root=temp;
}
void insertnode(node* &root,int x){//插入结点操作
    if(root==NULL){//到达空结点,即插入位置
        root=creatnode(x);
        return;
    }
    if(x<root->data){//x小于当前结点数据域
        insertnode(root->left,x);//应插入到左子树
        updataheight(root);//更新高度
        if(balancefactor(root)==2){
            if(balancefactor(root->left)==1)//LL型
                R(root);
            else{
                L(root->left);//LR型
                R(root);
            }
        }
    }
    else{//x大于当前结点数据域
        insertnode(root->right,x);//应插入到右子树
        updataheight(root);//更新高度
        if(balancefactor(root)==-2){
            if(balancefactor(root->right)==-1)//RR型
                L(root);
            else{
                R(root->right);//RL型
                L(root);
            }
        }
    }
}
int main(){
    int n,x;
    scanf("%d",&n);//输入结点总数
    node* root=NULL;//创建根节点指针,初始化为NULL
    for(int i=0;i<n;i++){
        scanf("%d",&x);//边读入边插入
        insertnode(root,x);
    }
    printf("%d",root->data);//输入根节点数据域
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值