7-3 Left-View of Binary Tree (25 分)
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), 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
结尾无空行
主要还是考察树的序列转换和遍历,输出层序遍历的第一个点就好了
AC代码:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int N;
vector<int> in,pre,le[20];
void trail(int root,int start,int end,int level){
if(start>end) return;
int index=pre[root];
le[level].push_back(index);
int i=start;
while(in[i]!=index) i++;
trail(root+1,start,i-1,level+1);
trail(root+i-start+1,i+1,end,level+1);
}
int main(){
cin>>N;
in.resize(N);
pre.resize(N);
for(int i=0;i<N;i++){
scanf("%d",&in[i]);
}
for(int i=0;i<N;i++){
scanf("%d",&pre[i]);
}
trail(0,0,N-1,0);
printf("%d",pre[0]);
for(int i=1;i<N;i++){
if(le[i].size()!=0){
printf(" %d",le[i][0]);
}else{
cout<<endl;
break;
}
}
return 0;
}