PAT 二叉树打卡

acwing:1605. 二叉搜索树最后两层结点数量

二叉搜索树 (BST) 递归定义为具有以下属性的二叉树:

  • 若它的左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值
  • 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值
  • 它的左、右子树也分别为二叉搜索树

将一系列数字按顺序插入到一个空的二叉搜索树中,然后,请你计算结果树的最低两层的结点个数。

输入格式

第一行包含整数 NN,表示插入数字序列包含的数字个数。

第二行包含 NN 个整数,表示插入数字序列。

输出格式

以如下格式,在一行中,输出结果树的最后两层的结点数:

复制代码
n1 + n2 = n

n1 是最底层结点数量,n2 是倒数第二层结点数量,n 是它们的和。

数据范围

1≤N≤10001≤N≤1000,

−1000≤−1000≤ 插入数字 ≤1000≤1000。

输入样例:
复制代码
9
25 30 42 16 20 20 35 -5 28
输出样例:
复制代码
2 + 4 = 6
cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
const int N=1010;

int n;

struct tree{
    int val;
    int h;
    int l,r;
}p[N];
int max_h;
int cnt[N];
void build(int root,int u,int h){
    if(p[root].val>=p[u].val){
        if(p[root].l==0x3f3f3f3f){
            p[root].l=u;
            p[u].h=h+1;
            max_h=max(max_h,p[u].h);
            //cout<<max_h<<endl;
            cnt[p[u].h]++;
        }else{
            build(p[root].l,u,h+1);
        }
    }else{
        if(p[root].r==0x3f3f3f3f){
            p[root].r=u;
            p[u].h=h+1;
            max_h=max(max_h,p[u].h);
           // cout<<max_h<<endl;
            cnt[p[u].h]++;
        }else{
            build(p[root].r,u,h+1);
        }
    }
}
void init()
{
    for(int i=0;i<N;i++){
        p[i].l=p[i].r=0x3f3f3f3f;
    }
} 
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    cin>>n;
    init();
    if(n==1){
        cout<<"1 + 0 = 1";
    }else{
        for(int i=1;i<=n;i++){
        int x;
        cin>>x;
        if(i==1){
            p[1].val=x;
            p[1].h=1;
        }else{
            p[i].val=x;
            build(1,i,1);
        }
       
    }
    //cout<<max_h<<endl;
    cout<<cnt[max_h]<<" + "<<cnt[max_h-1]<<" = "<<cnt[max_h]+cnt[max_h-1];
    }
    
}
相关推荐
万添裁14 小时前
huawei 机考
算法·华为·深度优先
IronMurphy21 小时前
【算法四十三】279. 完全平方数
算法
墨染天姬21 小时前
【AI】Hermes的GEPA算法
人工智能·算法
papership21 小时前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_7968265221 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
山甫aa1 天前
差分数组 ----- 从零开始的数据结构
数据结构
早日退休!!!1 天前
《数据结构选型指南》笔记
数据结构·数据库·oracle
Beginner x_u1 天前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
丑八怪大丑1 天前
Java数据结构与集合源码
数据结构
_深海凉_1 天前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展