二叉排序树的查找
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include
#include
#include
#define INFMT "%d"
#define OUTFMT "%d "
/* #define NULL 0L */
#define BOOL int
#define TRUE 1
#define FALSE 0
#define LEN 10000
typedef int ElemType;
typedef struct BSTNode
{
ElemType data;
struct BSTNode *lchild, *rchild;
} BSTNode, *BSTree;
/* 插入新节点*/
void Insert(BSTree *tree, ElemType item)
{
BSTree node = (BSTree)malloc(sizeof(BSTNode)); node->data = item;
node->lchild = node->rchild = NULL;
if (!*tree)
*tree = node;
else
{
BSTree cursor = *tree;
while (1)
{
if (item < cursor->data)
{
if (NULL == cursor->lchild)
{
cursor->lchild = node;
}
cursor = cursor->lchild;
}
else
{
if (NULL == cursor->rchild)
{
cursor->rchild = node;
break;
}
cursor = cursor->rchild;
}
}
}
return;
}
/* 查找指定值*/
BSTree Search(BSTree tree, ElemType item) {
BSTree cursor = tree;
while (cursor)
{
if (item == cursor->data)
return cursor;
else if ( item < cursor->data)
cursor = cursor->lchild;
else
cursor = cursor->rchild;
}
return NULL;
}
void Inorder(BSTree tree)
{
BSTree cursor = tree;
if (cursor)
{
Inorder(cursor->lchild);
printf(OUTFMT, cursor->data); Inorder(cursor->rchild);
}
}
/* 回收资源*/
void Cleanup(BSTree tree)
{
BSTree cursor = tree, temp = NULL;
if (cursor)
{
Cleanup(cursor->lchild);
Cleanup(cursor->rchild);
free(cursor);
}
}
/* 产生一组随机数*/
void randnum(int *a, int s)
{
int i, j, mod = s * 10;
srand(time(NULL));
for (i = 0; i < s; ++i)
{
a[i] = rand() % mod + 1;
for (j = 0; j < i; ++j)
{
if (a[i] == a[j])
{
a[i] = rand() % mod + 1;
j = -1;
continue;
}
}
}
}
void main()
{
ElemType item;
char choice;
BSTree root = NULL, ret; /* 必须赋予NULL值,否则出错*/ BOOL finish = FALSE;
printf("***欢迎使用二叉排序树演示程序***\n\n");
printf("请选择创建树的方式:\n");
printf("1. 手动输入数据创建二叉排序树\n");
printf("2. 自动产生数据创建二叉排序树\n");
do
{
scanf("%c", &choice);
getchar();
if (choice == '1' || choice == '2')
finish = TRUE;
} while (FALSE == finish);
switch (choice)
{
case '1':
{
printf("请输入数据(-10000结束):\n");