编写一个程序,实现如下操作:根据序列{40, 28, 6, 72, 100, 3, 54, 15, 80, 91}建立一棵二叉排序树。用括号表示法输出该二叉树。在该二叉树上查找30和80,给出结果。

 

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef int KeyType;
typedef int ElemType;
typedef struct bstnode
{    KeyType key;
    ElemType data;
    struct bstnode *leftchild,*rightchild;
}BSTNode;


int BSTInsert(BSTNode * &bt,KeyType k)
{    BSTNode *f,*p=bt;
    while(p!=NULL)
    {    if(p->key==k)
            return 0;
        f=p;
        if(k<p->key)
            p=p->leftchild;
        else
            p=p->rightchild;
    }
    p=(BSTNode * )malloc(sizeof(BSTNode));
    p->key=k;
    p->leftchild=p->rightchild=NULL;
    if(bt==NULL)
        bt=p;
    else if (k<f->key)
        f->leftchild=p;
    else
        f->rightchild=p;
    return 1;
}

void CreateBST(BSTNode * &bt,KeyType a[],int n)
{    bt=NULL;
    int i=0;
    while(i<n)
    {    BSTInsert(bt,a[i]);
        i++;
    }
}

void DestroyBST(BSTNode * &bt)
{    if(bt!=NULL)
    {    DestroyBST(bt->leftchild);
        DestroyBST(bt->rightchild);
        free(bt);
    }
}

void DispBST(BSTNode *bt)
{  if (bt!=NULL)
   {  printf("%d",bt->key);      
      if (bt->leftchild!=NULL || bt->rightchild!=NULL)
      {        printf("(");          
            DispBST(bt->leftchild);  
            if (bt->rightchild!=NULL) 
                printf(",");
            DispBST(bt->rightchild);  
            printf(")");          
        }
    }
}

BSTSearch(BSTNode *bt,KeyType k)
{  BSTNode *p=bt;
   while (p!=NULL)
   {    if (p->key == k)    
        {printf("\n\t与%d比较,相等\n",p->key);
        return 1;
        }
    else if (k < p->key)
        {printf("\n\t与%d比较,不相等\n",p->key);
         p=p->leftchild;    
        }
    else {printf("\n\t与%d比较,不相等\n",p->key);
         p=p->rightchild;
        }        
   }
   return 0;    
}

int main()
{    KeyType a[]={40,28,6,72,100,3,54,15,80,91},b,d,i,n=10;
    BSTNode *bt;
    CreateBST(bt,a,n);
    printf("初始序列:");
    for(i=0; i<n; i++)
    {d=a[i];printf("  %d  ",d);
    }
    printf("\n");
    printf("该二叉排序树的括号表示法:");
    DispBST(bt);
    printf("\n");
    printf("\n查找30:\n");
    b=BSTSearch(bt,30);
        if(b==0) printf("\n查找30失败\n");
            else printf("\n查找30成功\n");
    printf("\n查找80:\n");
    b=BSTSearch(bt,80);
        if(b==0) printf("\n查找80失败\n");
            else printf("\n查找80成功\n");    
                return 0;        
   
}
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柒月初一

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值