PAT-A-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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <queue>
using namespace std;
struct node {
int data;
node* lc, * rc;
node(int data) :data(data), lc(0), rc(0) {}
};

int postseq[30], inseq[30];

//用后序遍历和中序遍历构建树,并返回根节点
node* buildTree(int postL, int postR, int inL, int inR) {
if (postL > postR)
return 0;
node* root = new node(postseq[postR]);
int i;
for (i = inL;i <= inR;i++) {
if (root->data == inseq[i])
break;
}
//左子树的节点个数
int lnums = i - inL;
root->lc = buildTree(postL, postL + lnums - 1, inL, i - 1);
root->rc = buildTree(postL + lnums, postR - 1, i + 1, inR);
return root;
}

void levelOrder(node* root) {
queue<node*> q;
q.push(root);
node* temp;
int cnt = 0;
while (!q.empty()) {
temp = q.front();
q.pop();
if (cnt++ == 0)
printf("%d", temp->data);
else
printf(" %d", temp->data);
if (temp->lc!=0) {
q.push(temp->lc);
}
if (temp->rc != 0) {
q.push(temp->rc);
}

}
}

int main() {
int n, i, j;//节点的个数
scanf("%d", &n);
for (i = 0;i < n;i++)
scanf("%d", &postseq[i]);

for (j = 0;j < n;j++)
scanf("%d", &inseq[j]);

node* root = buildTree(0, n - 1, 0, n - 1);
levelOrder(root);

return 0;
}

----\(˙<>˙)/----赞赏一下吧~