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

//建树然后bfs，每层第一个数就直接输出，就maxLayer来判断是否是第一次出现这个层
#include<iostream>
#include<unordered_map>
#include<vector>
#include<queue>
using namespace std;
int n;
struct node{
int val;
node* lchild, *rchild;
int layer;
};
vector<int> inOrder(n+2);
vector<int> preOrder(n+2);
unordered_map<int,int> ma;
int maxLayer = -1;

node* buildTree(int preL,int preR,int inL,int inR){
if(preL > preR) return nullptr;
node* root = new node;
root->val = preOrder[preL];
root->lchild = root->rchild = nullptr;
int leftSubTree = ma[preOrder[preL]] - inL;
root->lchild = buildTree(preL+1,preL+leftSubTree,inL,inL+leftSubTree-1);
root->rchild = buildTree(preL+leftSubTree+1,preR,inL+leftSubTree+1,inR);
return root;
}

void bfs(node* s){
s->layer = 0;
queue<node*> q;
q.push(s);
bool flag = true;
while(!q.empty()){
node* topNode = q.front();
q.pop();
if(topNode->layer > maxLayer){
if(flag == true){
cout<<topNode->val;
maxLayer = topNode->layer;
flag = false;
}
else{
cout<<" "<<topNode->val;
maxLayer = topNode->layer;
}
}
if(topNode->lchild != nullptr){
topNode->lchild->layer = topNode->layer+1;
q.push(topNode->lchild);
}
if(topNode->rchild != nullptr){
topNode->rchild->layer = topNode->layer+1;
q.push(topNode->rchild);
}
}
}

int main(){
cin>>n;
for(int i = 0; i < n; i++){
cin>>inOrder[i];
}
for(int i = 0; i < n; i++){
cin>>preOrder[i];
}
for(int i = 0; i < n; i++){
ma[inOrder[i]] = i;
}
node* root = new node;
root = buildTree(0,n-1,0,n-1);
bfs(root);
return 0;
}

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

baixiaofei567

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

11-30 2296
03-24 220
07-28 115
12-27 66
04-01 322
12-17 2400
08-20
03-30
09-18
01-27