关于二叉排序树 BST

  1 #include
  2 #include
  3 
  4 typedef struct node
  5 {
  6     double w;
  7     struct node *l,*r;
  8 }*Node;
  9 
 10 void Build(Node &rt,double a)//建树
 11 {
 12     if(rt==NULL)
 13     {
 14         rt=new node;
 15         rt->w=a;
 16         rt->l=0;
 17         rt->r=0;
 18     }
 19     else
 20     {
 21         if(aw)
 22             Build(rt->l,a);
 23         else
 24             Build(rt->r,a);
 25     }
 26 }
 27 double fin(struct node *rt)  //找最小的权
 28 {
 29     if(!rt)
 30         return 0;
 31     else if(!rt->l)
 32         return rt->w;
 33     else
 34         return fin(rt->l);
 35 }
 36 
 37 void delet(Node &rt,double w)//删除权为w点
 38 {
 39     if(!rt)
 40     {
 41         printf("没有\n");
 42         return ;
 43     }
 44     else if(rt->w<w)
 45         delet(rt->r,w);
 46     else if(rt->w>w)
 47         delet(rt->l,w);
 48     else if(rt->l&&rt->r)
 49     {
 50         struct node *tmp;
 51         tmp=rt;
 52         tmp->w=fin(tmp->r);
 53         delet(tmp->r,tmp->w);
 54     }
 55     else
 56     {
 57         struct node *t;
 58         t=rt;
 59         if(rt->l)
 60             rt=rt->l;
 61         else
 62             rt=rt->r;
 63         delete(t);
 64     }
 65 
 66 }
 67 void in(struct node *rt) //中序
 68 {
 69     if(rt)
 70     {
 71         in(rt->l);
 72         printf("%lf ",rt->w);
 73         in(rt->r);
 74     }
 75     else
 76         return ;
 77 }
 78 double w;
 79 int aim;
 80 
 81 void search(Node rt,int &cnt) //找第aim小
 82 {
 83     if(rt)
 84     {
 85         search(rt->l,cnt);
 86         cnt++;
 87         if(cnt==aim)
 88         {
 89             w=rt->w;
 90             return;
 91         }
 92         search(rt->r,cnt);
 93 
 94     }    
 95 }
 96 int main()
 97 {
 98     int n;
 99     scanf("%d",&n);
100     struct node *root;
101     root=0;
102     for(int i=1;i<=n;i++) //插入
103     {
104         double a;
105         scanf("%lf",&a);
106         Build(root,a);
107     }
108     in(root);
109     printf("\n");
110     scanf("%d",&n);
111     for(int i=1;i<=n;i++)  //删除
112     {
113         double a;
114         scanf("%lf",&a);
115         delet(root,a);
116         in(root);
117         printf("\n");
118     }
119     scanf("%d",&n);
120     for(int i=1;i<=n;i++)
121     {
122         scanf("%d",&aim);  //第aim小
123         int cnt=0;
124         search(root,cnt);
125         printf("%lf\n",w);
126     }
127     return 0;
128 }
129 /*
130 9
131 3 4 2 5 7 6 3.5 3.1 3.6
132 0
133 3
134 6
135 7
136 3
137 
138 */

 

转载于:https://www.cnblogs.com/cherryMJY/p/6105244.html

你可能感兴趣的:(关于二叉排序树 BST)