PTA_L2-3 二叉搜索树的2层结点统计 (25 分)_二叉树

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

typedef struct AAA
{
    int v;
    struct AAA *x;
    struct AAA *y;
}A,*AA;
int ans,maxd;      

// 根据二叉搜索树的定义建树 
void build_tree( AA &tree,int v,int d )
{
    if( tree==NULL )
    {
        tree=new A;
        tree->v=v;
        tree->x=tree->y=NULL;
        maxd=max( maxd,d );
    }
    else if( v<=tree->v ) build_tree( tree->x,v,d+1 );
    else if( v>tree->v ) build_tree( tree->y,v,d+1 );
}

void aorder( AA tree,int d )    // 先序遍历
{
    if( tree==NULL ) return ;
    if( d>=maxd-1 ) ans++;
    aorder( tree->x,d+1 );
    aorder( tree->y,d+1 );
}

int main()
{
    int n,v,i;
    AA tree=NULL;
    
    cin>>n;
    while( n-- )
    {
        cin>>v; build_tree( tree,v,1 );
    }
    aorder( tree,1 );
    cout<<ans<<endl;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_63173957/article/details/124192654