PAT(甲级)1123

题意:给出一组数据,将他们插入到AVL树中,答案输出AVL树的层序遍历以及它是否是完全二叉树。
题解:一道显然的数据结构题,AVL树的四种旋转操作,树的插入,层序遍历,难点是如何判断完全二叉树,由于是层序遍历,如果遍历到一个空节点,那么它以后的节点应该全部为空,如果发现一个节点不为空,那么它就不是完全二叉树。
注意点:数据结构写正确,四种旋转操作和插入要写正确,代码量较大。
code in view

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+10;
int n;
int a[maxn];
vector<int> ans;
struct node{
    int val;
    node *left,*right;
};
node* RightRotate(node *root){
    node *temp=root->left;
    root->left=temp->right;
    temp->right=root;
    return temp;
}
node* LeftRotate(node *root){
    node *temp=root->right;
    root->right=temp->left;
    temp->left=root;
    return temp;
}
node* LeftRightRotate(node *root){
    root->left=LeftRotate(root->left);
    return RightRotate(root);
}
node* RightLeftRotate(node *root){
    root->right=RightRotate(root->right);
    return LeftRotate(root);
}
int get_height(node *root){
    if(root==NULL) return 0;
    int l=get_height(root->left);
    int r=get_height(root->right);
    return max(l,r)+1;
}
// 递归写法
node *insert(node *root,int val){
    if(root==NULL){
        root=new node();
        root->val=val;
    }else if(root->val>val){
        root->left=insert(root->left,val);
        int l=get_height(root->left);
        int r=get_height(root->right);
        if(l-r>=2){
            if(val<root->left->val) root=RightRotate(root);
            else root=LeftRightRotate(root);
        }
    }else{
        root->right=insert(root->right,val);
        int l=get_height(root->left);
        int r=get_height(root->right);
        if(r-l>=2){
            if(val<root->right->val) root=RightLeftRotate(root);
            else root=LeftRotate(root);
        }
    }
    return root;
}
bool flag,after;
void LevelOrder(node *root){
    queue<node*> q;
    q.push(root);
    ans.push_back(root->val);
    while(!q.empty()){
        node* temp=q.front();
        q.pop();
        if(temp->left!=NULL){
            if(after) flag=true;
            q.push(temp->left);
            ans.push_back(temp->left->val);
        }else{
            after=true;
        }
        if(temp->right!=NULL){
            if(after) flag=true;
            q.push(temp->right);
            ans.push_back(temp->right->val);
        }else{
            after=true;
        }
    }
}
int main(){
    cin>>n;
    node *tree=NULL;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        tree=insert(tree,a[i]);
    }
    LevelOrder(tree);
    for(int i=0;i<ans.size();i++){
        printf("%d%c",ans[i],i==ans.size()-1?'\n':' ');
    }
    printf("%s\n",flag==true?"NO":"YES");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值