编程实现二叉查找树的建立C语言,实现二叉排序树建立和检索算法(C语言)急求-rt 爱问知识人...

#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 data)

{

if (NULL == cursor->lchild)

{

cursor->lchild = node;

break;

}

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 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("***欢迎使用二叉排序树演示程序***

");

printf("请选择创建树的方式:

");

printf("1。

手动输入数据创建二叉排序树

");

printf("2。 自动产生数据创建二叉排序树

");

do

{

scanf("%c", &choice);

getchar();

if (choice == '1' || choice == '2')

finish = TRUE;

} while (FALSE == finish);

switch (choice)

{

case '1':

{

printf("请输入数据(-10000结束):

");

while (1)

{

scanf(INFMT, &item);

if (-10000 != item)

Insert(&root, item);

else

break;

}

break;

}

case '2':

{

int ia[LEN], i = 0, loop = LEN;

randnum(ia, LEN);

while (loop--)

{

Insert(&root, ia[i ]);

}

break;

}

}

printf("

创建完成。

。。

");

Inorder(root);

printf("

");

/* 二叉排序树的查找测试 */

do

{

printf("

请输入查找数据:");

scanf("%d", &item);

getchar();

printf("Searching。

。。

");

ret = Search(root, item);

if (NULL == ret)

printf("查找失败!");

else

printf("查找成功!");

printf("

继续测试按y,退出按其它键。

");

choice = getchar();

} while (choice=='y'||choice=='Y');

Cleanup(root);

}。

全部

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值