C/C++二叉排序树

来源:互联网 发布:国际淘宝什么意思 编辑:程序博客网 时间:2024/05/18 03:51
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. struct nodb
  4. {
  5.     int data;
  6.     struct nodb *lch,*rch;
  7. };
  8. struct nodb *root,*q,*p;
  9. void insert1(struct nodb *s);
  10. void creat()
  11. {
  12.     struct nodb *s;
  13.     int i,n,k;
  14.     printf("n=?");
  15.     scanf("%d",&n);
  16.     
  17.     for(i=1;i<n;i++)
  18.     {
  19.         printf("k%d=?",i);
  20.         scanf("%d",&k);
  21.         s=(struct nodb *)malloc(sizeof(struct nodb));
  22.         s->data=k;s->lch=NULL;s->rch=NULL;
  23.         insert1(s);
  24.     }
  25. }
  26. void insert1(struct nodb *s)
  27. {  //非递归插入
  28.     struct nodb *p,*q;
  29.     if(root==NULL)
  30.         root=s;
  31.     else
  32.     {
  33.         p=root;
  34.         while(p!=NULL)
  35.         {
  36.             q=p;//当p向子数节点移动时,q记录p的双亲的位置
  37.             if(s->data<p->data)
  38.                 p=p->lch;
  39.             else
  40.                 p=p->rch;
  41.         }
  42.         if(s->data<q->data)
  43.             q->lch=s;
  44.         else 
  45.             q->rch=s;//当p为空时,q就是可插入的地方
  46.     }
  47. }
  48. void print(struct nodb *t)
  49. {
  50.     if(t!=NULL)
  51.     {
  52.         print(t->lch);
  53.         printf("%6d",t->data);
  54.         print(t->rch);
  55.     }
  56. }
  57. void bstsrch(struct nodb*t,int k)
  58. {
  59.     int flag;
  60.     p=NULL;
  61.     q=t;
  62.     flag=0;
  63.     while((q!=NULL)&&(flag==0))
  64.     {
  65.         if(q->data==k)
  66.         {
  67.             printf("发现 %5d",q->data);
  68.             flag=1;
  69.         }
  70.         else if(k<q->data)
  71.         {
  72.             p=q;
  73.             q=q->lch;
  74.         }
  75.         else
  76.         {
  77.             p=q;
  78.             q=q->rch;
  79.         }
  80.     }
  81.     if(flag==0)printf("没有发现节点");
  82. }
  83. void bstins(struct nodb *t,int k)
  84. {
  85.     struct nodb *r;
  86.     bstsrch(root,k);
  87.     if(q==NULL)
  88.     {
  89.         r=(struct nodb*)malloc(sizeof(struct nodb));
  90.         r->data=k;
  91.         r->lch=NULL;
  92.         r->rch=NULL;
  93.         if(root==NULL)
  94.             root=r;
  95.         else if(k<p->data)
  96.             p->lch=r;
  97.         else
  98.             p->rch=r;
  99.     }
  100. }
  101. main()
  102. {
  103.     int n;
  104.     root=0;
  105.     creat();
  106.     print(root);
  107.     printf("请出入关键值n=?");
  108.     scanf("%d",&n);
  109.     bstsrch(root,n);
  110.     printf("/n");
  111.     bstins(root,n);
  112.     print(root);
  113. }

<script type="text/javascript"><!--google_ad_client = "pub-3555979289815451";google_ad_slot = "0437120238";google_ad_width = 468;google_ad_height = 60;//--></script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script>