pat 1123(AVL)

题意:给n个数,按照顺序插入AVL,输出层次遍历,如果这颗AVL是完全二叉树,输出YES 否则输出NO

当时考试的时候。忘记AVL什么时候旋转了,数据结构不会写,感觉药丸

判断完全二叉树,这个简单,是编号也好,根节点为1,左右儿子2*l,2*l+1,判断最大的编号是否是n即可

或者把每个节点插入队列,遇到nullptr停止,判断队列中是否剩下的有非nullptr节点

至于AVL的旋转,旋转没什么难得,记住就好

#include<bits/stdc++.h>
using namespace std;

struct node{
    int val;
    node *ch[2];
    node(){val=0;ch[0]=ch[1]=nullptr;}
    node(int val){this->val=val;ch[0]=ch[1]=nullptr;}
}*root;

void rotate(node* &rt,int d){
    node *t=rt->ch[d^1];rt->ch[d^1]=t->ch[d];t->ch[d]=rt;rt=t;
}

int gethight(node* root){
    if(root==nullptr)return 0;
    return max(gethight(root->ch[0]),gethight(root->ch[1]))+1;
}

void insert(node *&rt,int val){
    if(rt==nullptr){
        rt=new node(val);return ;
    }
    bool flag;
    int l,r;
    if(rt->val>val){
        flag=0;
        insert(rt->ch[0],val);
        l=gethight(rt->ch[0]);
        r=gethight(rt->ch[1]);
        if(l-r>1){
            if(val<rt->ch[0]->val)rotate(rt,1);
            else{
                rotate(rt->ch[0],0);
                rotate(rt,1);
            }
        }
    }
    else{
        flag=1;
        insert(rt->ch[1],val);
        l=gethight(rt->ch[0]);
        r=gethight(rt->ch[1]);
        if(r-l>1){
            if(val>rt->ch[1]->val)rotate(rt,0);
            else{
                rotate(rt->ch[1],1);
                rotate(rt,0);
            }
        }
    }
}

void print(){
    queue<node*> q;
    vector<int> ans;
    q.push(root);
    while(!q.empty()){
        node *t=q.front();q.pop();
        ans.push_back(t->val);
        if(t->ch[0])q.push(t->ch[0]);
        if(t->ch[1])q.push(t->ch[1]);
    }
    cout<<ans[0];
    for(int i=1;i<ans.size();i++)cout<<" "<<ans[i];cout<<endl;
    bool ok=1;
    q.push(root);
    while(q.front()!=nullptr){
        node* t=q.front();q.pop();
        q.push(t->ch[0]);
        q.push(t->ch[1]);
    }
    while(!q.empty()){
        node* t=q.front();q.pop();
        if(t!=nullptr)ok=0;
    }

    printf("%s
",ok?"YES":"NO");
}

int main(){
    root=nullptr;
    int n,v;
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>v;
        insert(root,v);
    }
    print();
    return 0;
}
原文地址:https://www.cnblogs.com/jihe/p/6489489.html