The left-view of a binary tree is a list of nodes obtained by looking at the tree from left hand side and from top down. For example, given a tree shown by the figure, its left-view is { 1, 2, 3, 4, 5 }
Given the inorder and preorder traversal sequences of a binary tree, you are supposed to output its left-view.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N ( ≤ 20 ) N (≤20) N(≤20), which is the total number of nodes in the tree. Then given in the following 2 lines are the inorder and preorder traversal sequences of the tree, respectively. All the keys in the tree are distinct positive integers in the range of int.
Output Specification:
For each case, print in a line the left-view of the tree. All the numbers in a line are separated by exactly 1 space, and there must be no extra space at the beginning or the end of the line.
Sample Input:
8
2 3 1 5 4 7 8 6
1 2 3 6 7 4 5 8
Sample Output:
1 2 3 4 5
Solution:
// Talk is cheap, show me the code
// Created by Misdirection 2021-09-08 14:19:22
// All rights reserved.
#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
using namespace std;
int inOrder[25], preOrder[25];
unordered_map<int, int> posInPre, posInMid;
vector<int> leftView;
struct Node{
int key;
Node *left;
Node *right;
Node(int k){
key = k;
left = NULL;
right = NULL;
}
~Node(){}
};
void findChildren(Node *r, int l1, int r1){
if(r == NULL || l1 >= r1) return;
int l2 = posInPre[r -> key];
int r2 = r1 - l1 + l2;
if(posInMid[r -> key] == l1) r -> right = new Node(preOrder[l2 + 1]);
else{
r -> left = new Node(preOrder[l2 + 1]);
if(posInMid[r -> key] != r1) r -> right = new Node(preOrder[posInMid[r -> key] - l1 + l2 + 1]);
}
if(r -> left != NULL) findChildren(r -> left, l1, posInMid[r -> key] - 1);
if(r -> right != NULL) findChildren(r -> right, posInMid[r -> key] + 1, r1);
}
void postTraverse(Node *r){
if(r == NULL) return;
if(r -> left != NULL) postTraverse(r -> left);
if(r -> right != NULL) postTraverse(r -> right);
cout << r -> key << ' ';
}
int main(){
int n;
scanf("%d", &n);
for(int i = 0; i < n; ++i){
scanf("%d", &inOrder[i]);
posInMid[inOrder[i]] = i;
}
for(int i = 0; i < n; ++i){
scanf("%d", &preOrder[i]);
posInPre[preOrder[i]] = i;
}
Node *root = new Node(preOrder[0]);
findChildren(root, 0, n - 1);
// postTraverse(root);
queue<Node*> q;
q.push(root);
while(!q.empty()){
int size = q.size();
for(int i = 0; i < size; ++i){
if(i == 0) leftView.push_back(q.front() -> key);
if(q.front() -> left != NULL) q.push(q.front() -> left);
if(q.front() -> right != NULL) q.push(q.front() -> right);
q.pop();
}
}
for(int i = 0; i < leftView.size(); ++i){
if(i == leftView.size() - 1) printf("%d\n", leftView[i]);
else printf("%d ", leftView[i]);
}
return 0;
}