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 (≤), 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

 

题意:

  给出一棵二叉树后序遍历和中序遍历的结果,要求输出这颗二叉树层序遍历的结果。

思路:

  首先我们可以根据中序遍历和后序遍历的规律来建立这颗二叉树,然后再层序遍历就好了。后序遍历序列的最后一个数字是根节点,然后通过中序遍历中根节点的位置我们可以计算出根节点左子树和右子树中节点的个数,进而将后序遍历的序列划分为两部分,然后进行递归就好了。

Code:

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 typedef struct Node* node;
 6 
 7 struct Node {
 8     int val;
 9     node left;
10     node right;
11     Node(int v) {
12         val = v;
13         left = NULL;
14         right = NULL;
15     }
16 };
17 
18 vector<int> postOrder;
19 vector<int> inOrder;
20 
21 int n;
22 
23 void LevelOrderTravel(node root) {
24     queue<node> que;
25     que.push(root);
26     bool isFirst = true;
27     while (!que.empty()) {
28         if (isFirst) {
29             isFirst = false;
30             cout << que.front()->val;
31         } else {
32             cout << " " << que.front()->val;
33         }
34         if (que.front()->left) que.push(que.front()->left);
35         if (que.front()->right) que.push(que.front()->right);
36         que.pop();
37     }
38 }
39 
40 node buildTree(int l1, int r1, int l2, int r2) {
41     if (l1 > r1 || l2 > r2) return NULL;
42     int val = postOrder[r1];
43     node root = new Node(val);
44     int pos = 0;
45     for (int i = l2; i <= r2; ++i) {
46         if (inOrder[i] == val) {
47             pos = i;
48             break;
49         }
50     }
51     int rightLen = r2 - pos;
52     int leftLen = pos - l2;
53     root->right = buildTree(r1 - rightLen, r1 - 1, pos + 1, r2);
54     root->left = buildTree(l1, l1 + leftLen - 1, l2, l2 + leftLen - 1);
55     return root;
56 }
57 
58 int main() {
59     cin >> n;
60     postOrder.resize(n + 1, 0);
61     inOrder.resize(n + 1, 0);
62     for (int i = 0; i < n; ++i) cin >> postOrder[i];
63     for (int i = 0; i < n; ++i) cin >> inOrder[i];
64     node root = buildTree(0, n - 1, 0, n - 1);
65     LevelOrderTravel(root);
66     return 0;
67 }

 

posted @ 2020-06-22 17:09  Veritas_des_Liberty  阅读(173)  评论(0编辑  收藏  举报