PAT(甲级)2020年秋季考试 7-3 Left-View of Binary Tree (25 分) 经验分享与心路历程

30分钟,过样例,最近都在整理过去的错题,来有意识的去记忆一些常考的模板,等考好我会把最后整理好的笔记发出来的

#include <bits/stdc++.h>
using namespace std;

struct node
{
    int val;
    node* left;
    node* right;
    int level;
    node() {
        left = right = NULL;
    }
};

vector<node> ans;
vector<int> in;
vector<int> pre;
int n;

node* build(int root, int start, int end) {
    if (start > end || root > n) {
        return NULL;
    }
    int i;
    for (i = 0; i < n; i++) {
        if (in[i] == pre[root]) {
            break;
        }
    }
    node* temp = new node();
    temp->val = in[i];
    temp->left = build(root + 1, start, i - 1);
    temp->right = build(root + 1 + i - start, i + 1, end);
    return temp;
}

void level_order(node* root) {
    queue<node*> q;
    root->level = 1;
    q.push(root);
    while (!q.empty()) {
        node* first = q.front();
        ans.push_back(*first);
        q.pop();
        if (first->left != NULL) {
            first->left->level = first->level+1;
            q.push(first->left);
        }
        if (first->right != NULL) {
            first->right->level = first->level+1;
            q.push(first->right);
        }
    }
}


int main()
{
#ifndef ONLINE_JUDGE
    FILE* s;
    freopen_s(&s, "in.txt", "r", stdin);
#endif // !ONLINE_JUDGE

    cin >> n;
    in.resize(n);
    pre.resize(n);
    int t;
    for (int i = 0; i < n; i++) {
        cin >> in[i]; 
    }
    for (int i = 0; i < n; i++) {
        cin >> pre[i];
    }
    node* root = build(0, 0, n - 1);
    level_order(root);
    bool chance = true;
    int match = 0;
    for (int i = 0; i < ans.size(); i++) {
        if (ans[i].level != match && chance == true) {
            cout << ans[i].val;
            chance = false;
            match = ans[i].level;
        }
        else if (ans[i].level != match && chance == false) {
            cout <<" "<< ans[i].val;
            match = ans[i].level;
        }
    }
    cout << endl;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Exodus&Focus

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

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值