[数据结构]第七次作业:二叉排序树

来源:互联网 发布:什么软件写日记最好 编辑:程序博客网 时间:2024/05/16 09:06

/* ==============  Program Description  ============= */
/*               Freshare's 7th of dswork             */
/* ================================================== */

#include "stdlib.h"
#include "stdio.h"
#define MAX 255
#define TRUE 1
#define FALSE 0
#define ElemType int

typedef struct BitNode
{
 ElemType data;
 struct BitNode *lchild,*rchild;
}BitNode,*BiTree;

BiTree find (BiTree root, ElemType key)
{
 BiTree p,f;
 p=root;
 while (p!=NULL)
  if (key<p->data) {f=p;p=p->lchild;}
  else {f=p;p=p->rchild;}
 return (f);
}

BiTree SearchBST(BiTree root ,int k)
{
 BiTree p;
 p=root;
 while(p!=NULL)
 if (p->data==k)  return(p);
  else if (k<p->data)  p=p->lchild;
  else p=p->rchild;
 return (NULL);
}

BiTree creadBiTree()
{
 BiTree root,f,p;
 int data;
 scanf("%d",&data);
 root=(BiTree)malloc(sizeof(BitNode));
 root->data=data;
 root->lchild=root->rchild=NULL;
 scanf("%d",&data);
 while(data!=9999)
 {
  f=find(root,data);
  p=(BitNode*)malloc(sizeof(BitNode));
  p->data=data;
  p->lchild=p->rchild=NULL;
  if(data<f->data)  f->lchild=p;
  else f->rchild=p;
  scanf("%d",&data);
 }
 return(root);
}

void main()
{
 BiTree root,p;
 int test;
 printf("输入数字,以9999结束:/n");
 root=creadBiTree();
 printf("请输入需要查找数据:/n");
    scanf("%d",&test);
 p=SearchBST(root,test);
 if (p!=NULL)  printf("%d被找到啦!/n",p->data);
 else printf("没有到啦!/n");
}

原创粉丝点击