pat1020. Tree Traversals (25)

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

提交代码

 

 1 #include<cstdio>
 2 #include<algorithm>
 3 #include<iostream>
 4 #include<cstring>
 5 #include<queue>
 6 #include<vector>
 7 #include<cmath>
 8 using namespace std;
 9 int post[35],in[35];
10 struct node{
11     int v;
12     node *l,*r;
13     node(){
14         l=r=NULL;
15     }
16 };
17 void BuildTree(int *post,int *in,int n,node *&h){
18     if(!n){
19         return;
20     }
21     h=new node();
22     int mid=post[n-1];
23     h->v=mid;
24     int i;
25     for(i=0;i<n;i++){
26         if(in[i]==mid){
27             break;
28         }
29     }
30     BuildTree(post,in,i,h->l);
31     BuildTree(post+i,in+i+1,n-1-i,h->r);
32 }
33 int main(){
34     int n,i;
35     node *h;
36     scanf("%d",&n);
37     for(i=0;i<n;i++){
38         scanf("%d",&post[i]);
39     }
40     for(i=0;i<n;i++){
41         scanf("%d",&in[i]);
42     }
43     BuildTree(post,in,n,h);
44     node cur;
45     queue<node> q;
46     q.push(*h);
47     printf("%d",h->v);
48     while(!q.empty()){
49         cur=q.front();
50         q.pop();
51         if(cur.l!=NULL){
52             q.push(*(cur.l));
53             printf(" %d",cur.l->v);
54         }
55         if(cur.r!=NULL){
56             q.push(*(cur.r));
57             printf(" %d",cur.r->v);
58         }
59     }
60     return 0;
61 }

 

posted @ 2015-08-27 09:26  Deribs4  阅读(167)  评论(0编辑  收藏  举报