1020. Tree Traversals (25)
时间限制
400 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue
Suppose that all the keys in a binary tree are distinct positive integers. Given the postorder and inorder traversal sequences, you are supposed to output the level order traversal sequence of the corresponding binary tree.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (<=30), the total number of nodes in the binary tree. The second line gives the postorder sequence and the third line gives the inorder sequence. All the numbers in a line are separated by a space.
Output Specification:
For each test case, print in one line the level order traversal sequence of the corresponding binary tree. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.
Sample Input:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
Sample Output:
4 1 6 3 5 7 2
提交代码
<pre style="margin-top: 0px; margin-bottom: 0px; padding: 0px; border: 0px; font-stretch: normal; line-height: 18px; font-family: 'Droid Sans Mono', Consolas, 'Courier New', monospace; vertical-align: baseline; overflow: auto; max-width: 868px;"><span class="preprocessor" style="margin: 0px; padding: 0px; border: 0px; font-style: inherit; font-variant: inherit; font-weight: inherit; font-stretch: inherit;font-size:undefined; line-height: inherit; font-family: inherit; vertical-align: baseline; color: rgb(85, 119, 153);"></span><pre name="code" class="cpp">#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
const int maxn=99999;
#define lson (root<<1)
#define rson (root<<1)+1
#define bug printf("---\n");
int n;
int T[maxn];
int post[maxn];
int in[maxn];
int vis[maxn];
int first=1;
void bfs(int root)
{
queue<int> q;
memset(vis,false,sizeof(vis));
vis[root]=true;
q.push(root);
while(!q.empty())
{
int root=q.front();
q.pop();
if(first)printf("%d",T[root]),first=0;
else printf(" %d",T[root]);
if(!vis[lson]&&T[lson]!=-1)
{
vis[lson]=true;
q.push(lson);
}
if(!vis[rson]&&T[rson]!=-1)
{
vis[rson]=true;
q.push(rson);
}
}
}
void build(int root,int pl,int pr,int il,int ir)
{
if(pl>pr){T[root]=-1;return;}
int p=il;
while(in[p]!=post[pr])p++;
T[root]=post[pr];
build(lson,pl,pr-ir+p-1,il,p-1);
build(rson,pr-ir+p,pr-1,p+1,ir);
}
int main()
{
int m,i,j,k,t;
// freopen("in.txt","r",stdin);
memset(T,-1,sizeof(T));
cin>>n;
for(i=0; i<n; i++)
cin>>post[i];
for(i=0; i<n; i++)
cin>>in[i];
build(1,0,n-1,0,n-1);
vector<int>v;
for(i=1;i<maxn;i++)if(T[i]!=-1)
v.push_back(T[i]);
m=v.size();
for(i=0;i<=m-2;i++)
printf("%d ",v[i]);
printf("%d\n",v[m-1]);
//bfs(1);
return 0;
}