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;
}

 

posted @ 2016-05-16 20:46  Fighting_Heart  阅读(163)  评论(0编辑  收藏  举报