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
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
int in[50],post[50];
struct node{
int val;
node *lchild;
node *rchild;
};
int n;
node* create(int in_l,int in_r,int post_l,int post_r){
if(post_r<post_l)
return NULL;
node *root = new node;
root->val=post[post_r];
//理解distinct含义:n个有区别的、不同的数字
//后序遍历 当前子树的最后一个结点是根,传入中序遍历中,划分得到左右子树
int k;
for(k=in_l;k<=in_r;k++)
if(in[k]==post[post_r])
break;
int numleft=k-in_l;
root->lchild=create(in_l,k-1,post_l,post_l+numleft-1);
root->rchild=create(k+1,in_r,post_l+numleft,post_r-1);
return root;
}
int cnt=0;
void BFS(node *root){
queue<node*>q;
q.push(root);
while(!q.empty()){
node *now=q.front();
q.pop();
printf("%d",now->val);
cnt++;
if(cnt<n) printf(" ");
if(now->lchild != NULL) q.push(now->lchild);
if(now->rchild != NULL) q.push(now->rchild);
}
}
int main(){
scanf("%d",&n);
//后序
for(int i=0;i<n;i++)
scanf("%d",&post[i]);
//中序
for(int i=0;i<n;i++)
scanf("%d",&in[i]);
node *root = create(0,n-1,0,n-1);
BFS(root);
return 0;
}