我的代码如下,主要就是第一次出现某个层次的点就打印:
#include <cstdio>
#include <vector>
#include <map>
// #define debug
int N, t;
std::vector<int> inorder, preorder;
std::map<int, int> loc;
bool flag[20];
void dfs(int inLeft, int inRight, int preLeft, int preRight, int level){
if (inRight < inLeft){
return;
}
if (!flag[level]){
printf("%s%d", level ? " " : "", preorder[preLeft]);
flag[level] = true;
}
int temp = loc[preorder[preLeft]];
dfs(inLeft, temp - 1, preLeft + 1, preLeft + temp - inLeft, level + 1);
dfs(temp + 1, inRight, preLeft + temp - inLeft + 1, preRight, level + 1);
}
int main(){
#ifdef debug
freopen("0.txt", "r", stdin);
freopen("1.txt", "w", stdout);
#endif
scanf("%d", &N);
for (int i = 0; i < N; ++i){
scanf("%d", &t);
inorder.push_back(t);
loc[t] = i;
}
for (int i = 0; i < N; ++i){
scanf("%d", &t);
preorder.push_back(t);
}
dfs(0, N - 1, 0, N - 1, 0);
#ifdef debug
fclose(stdin);
fclose(stdout);
#endif
return 0;
}
题目如下:
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