# PAT（甲级）2020年秋季考试 7-3 Left-View of Binary Tree

2020-12-06 17:22:54 乔梓鑫

## 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:

``````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<cstdio>
#include<queue>
#include<unordered_map>

using namespace std;

struct Node{
int data;
Node* left;
Node* right;
int level;
};

int N;//节点个数
int pre[30],in[30];
unordered_map<int,int> pos;//每一个节点在中序序列中的个数

Node* createTree(int preL,int preR,int inL,int inR){
if(preL>preR) return nullptr;
Node* root = new Node;
root->data = pre[preL];
int k = pos[root->data];// 根节点在中序中的位置
int numOfLeft = k-inL;
root->left = createTree(preL+1,preL+numOfLeft,inL,k-1);
root->right = createTree(preL+numOfLeft+1,preR,k+1,inR);
return root;
}

int currentLevel = 0;
vector<int> result;
void BFS(Node* root){
root->level = 1;
queue<Node*> q;
q.push(root);
while (!q.empty()){
Node* t = q.front();
q.pop();
if(currentLevel!=t->level){
// 到达节点层次转折处
result.push_back(t->data);
currentLevel = t->level;
}
if(t->left){
t->left->level = t->level+1;
q.push(t->left);
}
if(t->right){
t->right->level = t->level+1;
q.push(t->right);
}
}
}

int main(){
scanf("%d",&N);
for (int i = 0; i < N; ++i) {
scanf("%d",&in[i]);
pos[in[i]] = i;
}
for(int i=0;i<N;++i){
scanf("%d",&pre[i]);
}
Node* root = createTree(0,N-1,0,N-1);
BFS(root);
for(int i=0;i<result.size();++i){
printf("%d",result[i]);
if(i<result.size()-1) printf(" ");
}
return 0;
}``````

https://segmentfault.com/a/1190000038392721