PAT (Advanced Level) 1020. Tree Traversals (25)

Posted Fighting Heart

tags:

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

递归建树,然后BFS一下

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

const int maxn=40;
int a[maxn],b[maxn];
int n,tot;
struct Node
{
    int left;
    int right;
    int val;
}node[maxn];

void build(int L,int R,int fa,int f)
{
    int P=-1;
    for(int i=L;i<=R;i++)
        for(int j=1;j<=n;j++)
            if(b[i]==a[j]) P=max(P,j);

    int root_val=a[P];

    if(tot==0)
    {
        ++tot;
        node[tot].val=root_val;
    }
    else if(f==0)
    {
        ++tot;
        node[tot].val=root_val;
        node[fa].left=tot;
    }
    else if(f==1)
    {
        ++tot;
        node[tot].val=root_val;
        node[fa].right=tot;
    }

    int tmp=tot;

    for(int i=L;i<=R;i++)
    {
        if(b[i]==root_val)
        {
            if(i-L>0) build(L,i-1,tmp,0);
            if(R-i>0) build(i+1,R,tmp,1);
            break;
        }
    }

}

void bfs()
{
    queue<int>Q;
    Q.push(1);
    int cnt=0;
    while(!Q.empty())
    {
        int head=Q.front(); Q.pop();
        printf("%d",node[head].val); cnt++;
        if(cnt<n) printf(" ");
        else printf("\n");
        if(node[head].left!=-1) Q.push(node[head].left);
        if(node[head].right!=-1) Q.push(node[head].right);
    }
}

int main()
{
    scanf("%d",&n); tot=0;
    for(int i=1;i<=n;i++) scanf("%d",&a[i]);
    for(int i=1;i<=n;i++) scanf("%d",&b[i]);
    for(int i=0;i<=30;i++) node[i].left=node[i].right=-1;
    build(1,n,-1,-1);
    bfs();
    return 0;
}

 

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

PAT Advanced 1020 Tree Traversals (25分)

PAT (Advanced Level) 1025. PAT Ranking (25)

PAT Advanced Level 1044

PAT Advanced Level 1043

PAT Advanced Level 1079

PAT Advanced Level 1095