码迷,mamicode.com
首页 > 其他好文 > 详细

【PAT】1020 Tree Traversals (25)(25 分)

时间:2018-08-24 21:46:35      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:ace   cat   HERE   key   color   tree   tle   line   number   

1020 Tree Traversals (25)(25 分)

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

 

C++代码如下:

 1 #include<iostream>
 2 #include<queue>
 3 using namespace std;
 4 
 5 
 6 struct node {
 7     int data;
 8     node *lchild, *rchild;
 9 };
10 
11 int post[35], in[35];
12 int n;
13 
14 node* create(int posL,int posR,int inL,int inR) {
15     if (posL>posR) return NULL;
16     node *root = new node;
17     root->data = post[posR];
18     int k;
19     for (k = inL; k <=inR; k++) {
20         if (in[k] == post[posR]) break;
21     }
22     int numL = k-inL;
23     root->lchild = create(posL, posL + numL-1, inL,  k - 1);
24     root->rchild = create(posL + numL, posR - 1, k + 1, inR);
25     
26     return root;
27 }
28 
29 int num = 0;
30 
31 void level(node*r) {
32     if (r == NULL) return;
33     queue<node*>q;
34     q.push(r);
35     while (!q.empty()) {
36         node *top = q.front();
37         q.pop();
38         num++;
39         cout << top->data;
40         if (num < n) cout <<  ;
41         if (top->lchild != NULL) q.push(top->lchild);
42         if (top->rchild != NULL) q.push(top->rchild);
43     }
44 }
45 
46 int main() {
47     cin >> n;
48     int t;
49     for (int i = 0; i < n; i++) {
50         cin >> t;
51         post[i] = t;
52     }
53     for (int i = 0; i < n; i++) {
54         cin >> t;
55         in[i] = t;
56     }
57     node*root = create(0, n - 1, 0, n - 1);
58     level(root);
59     return 0;
60 }

【PAT】1020 Tree Traversals (25)(25 分)

标签:ace   cat   HERE   key   color   tree   tle   line   number   

原文地址:https://www.cnblogs.com/pgzhang/p/9532042.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!