二叉搜索树的2层结点统计

题目大意

在这里插入图片描述

主要思路

由于二叉搜索树是左子树上所有结点的值均小于或等于它的根结点的值,右子树上所有结点的值均大于它的根结点的值,所以我们每插入一个点就要从根节点dfs找到能存放该点的地方,也就是说如果这个值大于根节点就要往右找,小于等于根节点就要往左找,递归此过程,这样建树并且更新最大深度

AC代码

代码通俗易懂

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <string>
#include <cmath>
#include <queue>
#include <vector>
#include <map>
#include <sstream>
using namespace std;

const int N = 1010, INF = 0x3f3f3f3f;
int n, l[N], r[N], pos[N];
int cnt[N], max_depth;

void dfs(int root, int u, int depth)
{
    if(pos[u] <= pos[root])
    {
        if(l[root] == INF)
        {
            l[root] = u;
            cnt[depth+1]++;
            max_depth = max(max_depth, depth+1);
            return ;
        }
        else
        {
            dfs(l[root], u, depth + 1);
            return ;
        }
    }
    else
    {
        if(r[root] == INF)
        {
            r[root] = u;
            cnt[depth + 1]++;
            max_depth = max(max_depth, depth + 1);
            return ;
        }
        else
        {
            dfs(r[root], u, depth + 1);
            return ;
        }
    }
    
}

int main(void)
{
    memset(l, 0x3f, sizeof(l));
    memset(r, 0x3f, sizeof(r));
    cin >> n;
    if(n == 1)
    {
        cout << 1 << endl;
        return 0;
    }
    for(int i = 0; i < n; i++)
    {
        int x;
        cin >> x;
        if(!i)
        {
            pos[i] = x;
        }
        else
        {
            pos[i] = x;
            dfs(0, i, 0);
        }
    }

    cout << cnt[max_depth] + cnt[max_depth - 1] << endl;
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值