7-11 二叉搜索树的2层结点统计(C++)

二叉搜索树或者是一棵空树,或者是具有下列性质的二叉树:若它的左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值;若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;它的左、右子树也分别为二叉搜索树。

将一系列数字按给定顺序插入一棵初始为空的二叉搜索树,你的任务是统计结果树中最下面 2 层的结点数。

输入格式:输入在第一行给出一个正整数 N (≤1000),为插入数字的个数。第二行给出 N 个 [−1000,1000] 区间内的整数。数字间以空格分隔。

输出格式:在一行中输出最下面 2 层的结点总数。

输入样例:9
25 30 42 16 20 20 35 -5 28
输出样例:6

代码长度限制

16 KB

时间限制

400 ms

内存限制

64 MB

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

typedef struct Node {
    int val;
    Node* left;
    Node* right;
    int size; //子树数量
    int tall;//高度
}node, *pNode;

int max1 = 0;
int daan = 0;

//创建二叉搜索树
pNode buildTree(pNode &tree, int num,int tall){

    if(tree == NULL){
        tree = new node;  //开辟空间
        tree->val = num;  //赋值
        tree->left = tree->right = NULL;
        tree->tall = tall;//深度
        if(tall > max1){ //记录最大深度
            max1 = tall;
        }
 //cout << "22" << ' ' << tree->val <<endl;
        return tree;
    }

    //用二层搜索树的性质递归插入结点
    if(num <= tree->val){
        tree->left = buildTree(tree->left, num, tall+1);
    }
    else {
        tree->right = buildTree(tree->right, num, tall+1);
    }

    return tree;
}

//中序遍历
void inOrder(pNode &root){
    if(root == NULL)
        return;

    inOrder(root->left);
    if(root->tall >= max1-1){  //如果是最下两层,答案daan+1
        daan++;
    }
    inOrder(root->right);

}



int main(){
    int n;
    cin >> n;
    int num;
    node *root = NULL;
    for(int i = 0; i < n; i++){
        cin >> num;
        buildTree(root, num, 1);
    }
    //cout << max1 << endl;
    inOrder(root);
    cout << daan;

    return 0;
}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

百年bd

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

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

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

打赏作者

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

抵扣说明:

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

余额充值