给定一棵二叉树的后序遍历和中序遍历,请你输出其层序遍历的序列。这里假设键值都是互不相等的正整数。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
4 1 6 3 5 7 2
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<queue>
using namespace std;
int mid[100],post[100],pre[100];
int s,n;
struct node{
int c;
node *lc,*rc;
};
node *solo(int k,int *mid,int *post)
{
int i,j;
if(k<=0)
return 0;
node *p;
p = new node;
p->lc = p-> rc = NULL;
p->c = post[k-1];
for(i = 0;i < n;++ i)
if(mid[i] == post[k-1])
break;
for(j = 0;j < n;++ j)
if(*mid==mid[j]) break;
int l=i-j;
p->lc = solo(l,mid,post);
p->rc = solo(k-l-1,mid+l+1,post+l);
return p;
}
void layer(node *head){
queue<node *>Q;
while(!Q.empty())
Q.pop();
Q.push(head);
while(!Q.empty()){
node *u;
u = Q.front();Q.pop();
pre[s++] = u->c;
if(u->lc)
Q.push(u->lc);
if(u->rc)
Q.push(u->rc);
}
}
int main()
{
int k,i;
while(~scanf("%d",&n)){
for(i = 0;i < n;++ i){
scanf("%d",&post[i]);
}
for(i = 0;i < n;++ i){
scanf("%d",&mid[i]);
}
s=0;
node *head = new node;
head->lc = head->rc = NULL;
head = solo(n,mid,post);
layer(head);
for(i = 0 ;i < s;++ i){
printf(i==s-1?"%d\n":"%d ",pre[i]);
}
}
return 0;
}