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 ) N (≤30) 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
Solution:
// Talk is cheap, show me the code
// Created by Misdirection 2021-08-12 15:28:46
// All rights reserved.
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
using namespace std;
int n;
vector<int> post;
vector<int> in;
unordered_map<int, bool> hasFound;
struct Node{
int num;
Node *left;
Node *right;
Node(int n = -1, Node* l = NULL, Node* r = NULL){
num = n;
left = l;
right = r;
}
~Node(){}
};
void findChildren(Node *r){
// printf("finding %d's children\n", r -> num);
int inPos, postPos;
for(int i = 0; i < n; ++i){
if(in[i] == r -> num){
inPos = i;
break;
}
}
for(int i = 0; i < n; ++i){
if(post[i] == r -> num){
postPos = i;
break;
}
}
bool findLeft = false, findRight = false;
for(int i = postPos - 1; i >= 0; --i){
for(int j = 0; j < inPos; ++j){
if(post[i] == in[j] && hasFound[post[i]] == false){
r -> left = new Node(post[i], NULL, NULL);
// printf("%d's left children is %d\n", r -> num, post[i]);
findLeft = true;
hasFound[post[i]] = true;
break;
}
}
if(findLeft) break;
}
for(int i = postPos - 1; i >= 0; --i){
for(int j = inPos + 1; j < n; ++j){
if(post[i] == in[j] && hasFound[post[i]] == false){
r -> right = new Node(post[i], NULL, NULL);
// printf("%d's right children is %d\n", r -> num, post[i]);
findRight = true;
hasFound[post[i]] = true;
break;
}
}
if(findRight) break;
}
if(r -> left != NULL) findChildren(r -> left);
if(r -> right != NULL) findChildren(r -> right);
return;
}
int main(){
cin >> n;
post.resize(n);
in.resize(n);
for(int i = 0; i < n; ++i) cin >> post[i];
for(int i = 0; i < n; ++i){
cin >> in[i];
hasFound[in[i]] = false;
}
Node *root = new Node(post[n - 1], NULL, NULL);
hasFound[post[n - 1]] = true;
findChildren(root);
queue<Node*> q;
q.push(root);
while(!q.empty()){
printf("%d", q.front() -> num);
if(q.front() -> left != NULL) q.push(q.front() -> left);
if(q.front() -> right != NULL) q.push(q.front() -> right);
q.pop();
if(q.empty()) printf("\n");
else printf(" ");
}
return 0;
}