PAT (Advanced Level) 1110. Complete Binary Tree (25)

Posted Fighting Heart

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了PAT (Advanced Level) 1110. Complete Binary Tree (25)相关的知识,希望对你有一定的参考价值。

判断一棵二叉树是否完全二叉树。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<map>
#include<queue>
#include<stack>
#include<algorithm>
using namespace std;

int n,root;
const int maxn=30;
struct Node
{
    int left;
    int right;
    int dep;
} s[maxn];
int flag[maxn];
vector<int>g[maxn];
int Max_dep=0;

void dfs(int x,int dep)
{
    Max_dep=max(dep,Max_dep);
    s[x].dep=dep;
    g[dep].push_back(x);

    if(s[x].left!=-1) dfs(s[x].left,dep+1);
    if(s[x].right!=-1) dfs(s[x].right,dep+1);
}

int main()
{
    memset(flag,0,sizeof flag);
    scanf("%d",&n);
    for(int i=0; i<n; i++)
    {
        char L[5],R[5];
        scanf("%s%s",L,R);
        if(L[0]==-) s[i].left=-1;
        else
        {
            int num=0;
            for(int k=0; L[k]; k++) num=num*10+L[k]-0;
            s[i].left=num;
            flag[num]=1;
        }

        if(R[0]==-) s[i].right=-1;
        else
        {
            int num=0;
            for(int k=0; R[k]; k++) num=num*10+R[k]-0;
            s[i].right=num;
            flag[num]=1;
        }
    }

    for(int i=0; i<n; i++)
        if(flag[i]==0) root=i;

    dfs(root,0);

    if(Max_dep==0)
    {
        printf("YES %d\n",g[Max_dep][g[Max_dep].size()-1]);
    }
    else
    {
        bool fail=0;
        for(int i=0; i<=Max_dep; i++)
        {
            if(i<Max_dep)
            {
                if(g[i].size()==(int)pow(2.0,i)) {}
                else fail=1;
            }
            else
            {
                for(int j=0; j<g[i].size(); j=j+2)
                {
                    if(j+1<g[i].size()&&j<g[i].size())
                    {
                        if(s[g[i-1][j/2]].left==g[i][j]&&s[g[i-1][j/2]].right==g[i][j+1]) {}
                        else fail=1;
                    }
                    else
                    {
                        if(s[g[i-1][j/2]].left==g[i][j]) {}
                        else fail=1;
                    }
                }
            }
        }

        if(fail==1) printf("NO %d\n",root);
        else printf("YES %d\n",g[Max_dep][g[Max_dep].size()-1]);
    }
    return 0;
}

 

以上是关于PAT (Advanced Level) 1110. Complete Binary Tree (25)的主要内容,如果未能解决你的问题,请参考以下文章

PAT Advanced Level 1044

PAT Advanced Level 1043

PAT Advanced Level 1079

PAT Advanced Level 1095

PAT Advanced Level 1038

pat advanced level 1063