1115 Counting Nodes in a BST (30 分)【难度: 一般 / 知识点: 构建二叉搜索树】

在这里插入图片描述
https://pintia.cn/problem-sets/994805342720868352/problems/994805355987451904
很经典的构建搜索二叉树。

#include<bits/stdc++.h>
using namespace std;
const int N=1e4+10;
int l[N],r[N],w[N],idx,n,x;
int cnt[N],maxv;
void insert(int &u,int c)//注意一定要引用。
{
    
    
    if(!u)//无结点
    {
    
    
        u=++idx;//构建结点
        w[u]=c;
    }else if(w[u]>=c) insert(l[u],c);//左边插入
    else insert(r[u],c);//右边插入
}
void dfs(int u,int deep)
{
    
    
    cnt[deep]++;
    maxv=max(maxv,deep);
    if(l[u]) dfs(l[u],deep+1);
    if(r[u]) dfs(r[u],deep+1);
}
int main(void)
{
    
    
    int root=0;
    cin>>n;
    for(int i=0;i<n;i++)
    {
    
    
        cin>>x;
        insert(root,x);
    }
    dfs(root,0);
    printf("%d + %d = %d\n",cnt[maxv],cnt[maxv-1],cnt[maxv]+cnt[maxv-1]);
    return 0;
}

Supongo que te gusta

Origin blog.csdn.net/qq_46527915/article/details/121454795
Recomendado
Clasificación