PAT甲级1115 Counting Nodes in a BST (30分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

在这里插入图片描述

​​Output Specification:

在这里插入图片描述

Sample Input:

9
25 30 42 16 20 20 35 -5 28

Sample Output:

2 + 4 = 6

二、解题思路

算是一道比较简单的30分题,给我们一组数据,要求我们放入BST中并且输出最后两层的元素数目之和。BST的插入操作利用递归即可实现,对于每层的元素数目,我们可以利用层序遍历,用cnt数组存放,最后输出即可。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
const int maxn = 1010;
int maxlevel = 0;
int cnt[maxn] = {0};
struct Node
{
    int key, layer; //存放的值,该结点所在的层数
    Node* lchild;   //左孩子
    Node* rchild;   //右孩子
};
void insertNode(Node* &root, int x) //BST的插入操作
{
    if(root == NULL)
    {
        root = new Node();
        root->key = x;
        root->lchild = NULL;
        root->rchild = NULL;
        return;
    }
    if(x <= root->key)  insertNode(root->lchild, x);
    if(x > root->key)   insertNode(root->rchild, x);
}
int main()
{
    int N, tmp;
    Node* root = NULL;  //一定要初始化
    scanf("%d", &N);
    for(int i=0; i<N; i++)
    {
        scanf("%d", &tmp);
        insertNode(root, tmp);
    }
    queue<Node*> q;
    q.push(root);
    root->layer = 1;
    while(!q.empty())   //层序遍历开始
    {
        Node* now = q.front();
        q.pop();
        cnt[now->layer]++;  //更新cnt数组
        if(now->layer > maxlevel)   maxlevel = now->layer;  //更新最大层数
        if(now->lchild != NULL)
        {
            now->lchild->layer = now->layer + 1;
            q.push(now->lchild);
        }
        if(now->rchild != NULL)
        {
            now->rchild->layer = now->layer + 1;
            q.push(now->rchild);
        }
    }
    printf("%d + %d = %d", cnt[maxlevel], cnt[maxlevel - 1], cnt[maxlevel] + cnt[maxlevel - 1]);    //输出最后两层的结点数即可
    return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值