1020 Tree Traversals

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:

1
2
3
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7

Sample Output:

1
4 1 6 3 5 7 2

Code

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
#include 
#include
using namespace std;
int n;
struct TNode{
int data;
TNode *lchild;
TNode *rchild;
};

TNode* create(int post[],int in[],int postL,int postR,int inL,int inR){
if(postL>postR)
return NULL;
TNode *p = new TNode;
p->data = post[postR];
int pos;
for(pos=inL;in[pos]!=post[postR]&&pos<=inr;pos++);< span>
int num = pos-inL;
p -> lchild = create(post,in,postL,postL+num-1,inL,pos-1);
p -> rchild = create(post,in,postL+num,postR-1,pos+1,inR);
return p;
}
void level_order(TNode *T){
queue q;
TNode *p;
q.push(T);
int num=0;
while(!q.empty()){
p = q.front();
printf("%d",p->data);
num++;
if(num
printf(" ");
q.pop();
if(p->lchild != NULL) q.push(p->lchild);
if(p->rchild != NULL) q.push(p->rchild);
}
}
int main(){
TNode* T;
scanf("%d", &n);
int post[n],in[n];
for(int i=0;i
scanf("%d", &post[i]);
for(int i=0;i
scanf("%d", &in[i]);
T = create(post,in,0,n-1,0,n-1);
level_order(T);
return 0;
}
丨fengche丨 wechat
来找我聊天吧~
-------------本文结束感谢您的阅读-------------