【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 }

 

posted @ 2020-02-20 00:06  sewage  阅读(187)  评论(0编辑  收藏  举报