zoukankan      html  css  js  c++  java
  • 【PAT甲级】1115 Counting Nodes in a BST (30分)(二叉查找树)

    题意:

    输入一个正整数N(<=1000),接着输入N个整数([-1000,1000]),依次插入一棵初始为空的二叉排序树。输出最底层和最底层上一层的结点个数之和,例如x+y=x+y。

    AAAAAccepted code:

     1 #define HAVE_STRUCT_TIMESPEC
     2 #include<bits/stdc++.h>
     3 using namespace std;
     4 typedef struct Node{
     5     int value;
     6     int vis;
     7     int level;
     8     int visl,visr;
     9     Node *lchild,*rchild;
    10 }node;
    11 int a[1007];
    12 int num[1007];
    13 void insert_(node *now,int x,int y){
    14     if(now->vis==0){
    15         now->value=x;
    16         now->vis=1;
    17         now->level=y;
    18         ++num[y];
    19         return ;
    20     }
    21     if(x<=now->value){
    22         if(now->visl==0){
    23             now->lchild=new node();
    24             now->visl=1;
    25         }
    26         insert_(now->lchild,x,1+y);
    27     }
    28     else{
    29         if(now->visr==0){
    30             now->rchild=new node();
    31             now->visr=1;
    32         }
    33         insert_(now->rchild,x,1+y);
    34     }
    35     return ;
    36 }
    37 int main(){
    38     ios::sync_with_stdio(false);
    39     cin.tie(NULL);
    40     cout.tie(NULL);
    41     int n;
    42     cin>>n;
    43     for(int i=1;i<=n;++i)
    44         cin>>a[i];
    45     node *root=new node();
    46     root->value=a[1];
    47     root->vis=1;
    48     root->level=0;
    49     ++num[0];
    50     for(int i=2;i<=n;++i)
    51         insert_(root,a[i],0);
    52     int mx=0;
    53     for(int i=0;i<n;++i)
    54         if(num[i])
    55             mx=i;
    56     cout<<num[mx]<<" + "<<num[mx-1]<<" = "<<num[mx]+num[mx-1];
    57     return 0;
    58 }
    保持热爱 不懈努力 不试试看怎么知道会失败呢(划掉) 世上无难事 只要肯放弃(划掉)
  • 相关阅读:
    C、C++混合调用
    20211027 投资策略优化
    2021投资策略
    程序猿多个对象的友好管理方式IOC容器
    欧几里德算法--求最大公约数
    C语言查找一个字符串中指定字符的个数
    linux下OpenSSL的RSA密钥生成
    文章目录
    python之禅
    EF 6.0 与sql ce 4.0 程序示例
  • 原文地址:https://www.cnblogs.com/ldudxy/p/12334003.html
Copyright © 2011-2022 走看看