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 \leq20 ≤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
思路
根据先序遍历和中序遍历建树,然后层序遍历,每层的第一个节点存下来,最后输出就是答案
cpp代码
#include<iostream>
#include<unordered_map>
#include<vector>
#include<queue>
using namespace std;
unordered_map<int,int> pos,l,r;
const int N=30;
int in[N],pre[N];
int n;
int build(int inl,int inr,int prel,int prer){
int root=pre[prel];
int k=pos[root];
if(k>inl)l[root]=build(inl,k-1,prel+1,k-1-inl+prel+1);
if(k<inr)r[root]=build(k+1,inr,k-1-inl+prel+1+1,prer);
return root;
}
void bfs(int root){
queue<int> q;
q.push(root);
vector<int> vec;
while(q.size()){
int len=q.size();
vec.push_back(q.front());
for(int i=0;i<len;i++){
auto t=q.front();
q.pop();
if(l.count(t))q.push(l[t]);
if(r.count(t))q.push(r[t]);
}
}
cout<<vec[0];
for(int i=1;i<vec.size();i++){
cout<<" "<<vec[i];
}
puts("");
}
int main(){
cin>>n;
for(int i=0;i<n;i++){
cin>>in[i];
pos[in[i]]=i;
}
for(int i=0;i<n;i++)cin>>pre[i];
int root=build(0,n-1,0,n-1);
bfs(root);
return 0;
}