PATA1115_BST(二叉查找树)

这篇博客讨论了一道PAT编程竞赛题,涉及二叉搜索树(BST)的构建和层次遍历。作者使用C++实现了一个BST,并通过层次遍历计算最大层数及其节点数量。代码中,`mp`映射存储各层次节点数,`maxLayer`记录最大层数,`v`用于层次遍历。博客最后给出了计算 BST 最大层和次大层节点总数的表达式。

记得BST的定义根据题目需求改一下就ok了,这次pat全是送分的QAQ。

#include <bits/stdc++.h>
using namespace std;
int maxLayer = 0;
map<int, int> mp;
vector<vector<int>> v(5);
struct node {
    int val, layer;
    struct node *lc, *rc;
};
node *build (int val, int layer, node *tree) {
    if (tree == NULL) {
        tree = new node();
        tree->val = val;
        tree->layer = layer;
        mp[layer]++;
    }
    else if (val <= tree->val) 
        tree->lc = build (val, layer + 1, tree->lc);
    else if (val > tree->val)
        tree->rc = build (val, layer + 1, tree->rc);
    if (layer > maxLayer) maxLayer = layer;
    return tree;
}
int main() {
    int n, a;
    node *root = NULL;
    scanf ("%d", &n);
    for (int i = 0; i < n; i++) {
        scanf ("%d", &a);
        root = build (a, 0, root);
    }
    queue<node*> q;
    q.push(root);
    while (!q.empty()) {
        node *now = q.front();
        q.pop();
        if (now->lc != NULL) q.push(now->lc);
        if (now->rc != NULL) q.push(now->rc);
    }
    printf ("%d + %d = %d", mp[maxLayer], mp[maxLayer - 1], mp[maxLayer] + mp[maxLayer - 1]);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值