1020 Tree Traversals (25 point(s))
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
Example:
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct Order {
int postBegin;
int postEnd;
int inBegin;
int inEnd;
};
int main()
{
int N;
cin >> N;
if(N == 0) return 0;
vector<int> postOrder(N);
vector<int> inOrder(N);
for(int i = 0; i < N; i++) cin >> postOrder[i];
for(int i = 0; i < N; i++) cin >> inOrder[i];
queue<Order> Q;
Q.push({0, N, 0, N});
int count = 0;
while(!Q.empty()) {
Order &x = Q.front();
int root = postOrder[x.postEnd-1];
cout << (count++==0 ? "" : " ") << root;
if(x.inEnd - x.inBegin > 1) {
int i = x.inBegin;
while(i < x.inEnd) {
if(inOrder[i] == root) break;
i++;
}
int left = i - x.inBegin;
if(left > 0)
Q.push({x.postBegin, x.postBegin+left, x.inBegin, x.inBegin+left});
int right = x.inEnd - i - 1;
if(right > 0)
Q.push({x.postBegin+left, x.postEnd-1, x.inBegin+left+1, x.inEnd});
}
Q.pop();
}
}
思路:
后根遍历的最后一位是树根,中根遍历在树根前是左子树,后面是右子树;
判断子数结点数大于0,则进队等候处理