PAT (Advanced Level) Practice 1127 ZigZagging on a Tree (30 分)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Nightmare_ak/article/details/84873179
#include<cstdio>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;

const int N=30+5;

struct Node
{
    int u,lev;
};

int in[N],post[N],key[N],ch[N][2],rt,dfn;
vector<int> res[N];

int build(int l,int r,int L,int R)
{
    if(r<l) return 0;
    int now=++dfn;key[now]=post[r];
    for(int i=L;i<=R;i++)
        if(in[i]==post[r])
        {
            int len=i-L;
            ch[now][0]=build(l,l+len-1,L,i-1);
            ch[now][1]=build(l+len,r-1,i+1,R);
            break;
        }
    return now;
}

void bfs(int s)
{
    queue<Node> q;
    q.push({s,0});
    while(!q.empty())
    {
        Node u=q.front();
        q.pop();
        res[u.lev].push_back(key[u.u]);
        if(ch[u.u][0]) q.push({ch[u.u][0],u.lev+1});
        if(ch[u.u][1]) q.push({ch[u.u][1],u.lev+1});
    }
}

int main()
{
    dfn=0;
    int n;scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d",in+i);
    for(int i=1;i<=n;i++)
        scanf("%d",post+i);
    rt=build(1,n,1,n);
    bfs(rt);
    int cnt=0;
    for(int i=0;i<N;i++)
        for(int j=0;j<res[i].size();j++)
        {
            int now=j;
            if(i%2==0) now=res[i].size()-1-j;
            if(cnt) printf(" ");
            printf("%d",res[i][now]);
            cnt++;
        }
    puts("");
    return 0;
}

猜你喜欢

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