PAT (Advanced Level) Practice 1123 Is It a Complete AVL Tree (30 分)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Nightmare_ak/article/details/84870400

判断完全二叉树:后续节点如果有儿子节点,那么前面的节点必须都有两个儿子节点

#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;

const int N=20+5;

int rt,ch[N][2],key[N],dfn,is;
vector<int> ans;

int getH(int u)
{
    if(u==0) return 0;
    return max(getH(ch[u][0]),getH(ch[u][1]))+1;
}

int LL(int u)
{
    int ls=ch[u][0];
    ch[u][0]=ch[ls][1];
    ch[ls][1]=u;
    return ls;
}

int RR(int u)
{
    int rs=ch[u][1];
    ch[u][1]=ch[rs][0];
    ch[rs][0]=u;
    return rs;
}

int LR(int u)
{
    ch[u][0]=RR(ch[u][0]);
    return LL(u);
}

int RL(int u)
{
    ch[u][1]=LL(ch[u][1]);
    return RR(u);
}

int insert(int u,int x)
{
    if(u==0)
    {
        key[++dfn]=x;
        return dfn;
    }
    if(x<key[u])
    {
        ch[u][0]=insert(ch[u][0],x);
        if(getH(ch[u][0])-getH(ch[u][1])>1)
        {
            if(x<key[ch[u][0]]) u=LL(u);
            else u=LR(u);
        }
    }
    else
    {
        ch[u][1]=insert(ch[u][1],x);
        if(getH(ch[u][1])-getH(ch[u][0])>1)
        {
            if(x>=key[ch[u][1]]) u=RR(u);
            else u=RL(u);
        }
    }
    return u;
}

void bfs(int s)
{
    queue<int> q;
    q.push(s);
    int f=1;
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        ans.push_back(key[u]);
        if(!ch[u][0]&&!ch[u][1]) f=0;
        else if(ch[u][0]&&!ch[u][1])
        {
            if(!f) is=0;
            q.push(ch[u][0]),f=0;
        }
        else if(!ch[u][0]&&ch[u][1]) q.push(ch[u][1]),is=0;
        else
        {
            if(!f) is=0;
            q.push(ch[u][0]),q.push(ch[u][1]);
        }
    }
}

int main()
{
    int n;scanf("%d",&n);
    rt=0,dfn=0;
    for(int i=1;i<=n;i++)
    {
        int x;scanf("%d",&x);
        rt=insert(rt,x);
    }
    is=1;
    bfs(rt);
    for(int i=0;i<ans.size();i++)
        printf("%d%c",ans[i]," \n"[i+1==ans.size()]);
    if(is) puts("YES");
    else puts("NO");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Nightmare_ak/article/details/84870400