PAT A1020

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include "stdio.h"
//#include "math.h"
#include "string.h"
//#include "iostream"
//#include "stdlib.h"
#include "vector"
//#include "set"
//#include "map"
//#include "stack"
#include "queue"
#include "algorithm"
using namespace std;

//typedef long long LL;
const int maxn = 50;
struct node{
int data;
node* lchild;
node* rchild;
};
int pre[maxn], in[maxn], post[maxn];//先序,中序以及后序
int n;//结点个数
//当前二叉树后序序列区间为[postL,postR], 中序序列区间为[inL, inR]
//create函数返回构建出的二叉树的根节点地址
node* create(int postL,int postR, int inL, int inR){
if (postL > postR) {
return NULL;//若后序序列长度小于0,则直接返回
}
node* root = new node;//新建一个结点,用来存放当前二叉树的根节点
root->data = post[postR];//新结点的数据域为根结点的值
int k;//k为根节点的值在中序序列中的位置
for (k = inL; k <= inR; k++) {
if (in[k] == post[postR]) {//如果在中序序列中找到了
break;
}
}
int numLeft = k - inL;//左子树的结点个数
//返回左子树的根结点地址,赋值给root的左指针
root->lchild = create(postL, postL + numLeft - 1, inL, k - 1);
//返回右子树的根节点地址,赋值给root的右指针
root->rchild = create(postL + numLeft, postR - 1, k + 1, inR);
return root;
}
int num = 0;//已输出的结点个数
void BFS(node* root){
queue<node*> q;//注意队列里面储存的是地址
q.push(root);//将根节点地址入队
while (!q.empty()) {
node* now = q.front();//取出队首元素
q.pop();
printf("%d", now->data);//打印队首元素
num++;
if (num < 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;
}