实现二叉排序树建立和检索算法(C语言)【急求】

rt

#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#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;
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 < 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");

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("\n\n创建完成...\n");
Inorder(root);
printf("\n\n");

/* 二叉排序树的查找测试 */
do
{
printf("\n请输入查找数据:");
scanf("%d", &item);
getchar();
printf("Searching...\n");
ret = Search(root, item);

if (NULL == ret)
printf("查找失败!");
else
printf("查找成功!");

printf("\n继续测试按y,退出按其它键。\n");
choice = getchar();
} while (choice=='y'||choice=='Y');

Cleanup(root);
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-06-03
朋友,看看这个是不是你要的,不过好像是C++的,C编的二叉树的程序真的不多。

http://www.pudn.com/downloads55/sourcecode/windows/csharp/detail192173.html
调用建立二叉排序树,检索给定值,插入/删除给定指针所指结点各算法

下面是 下载链接,如果你不会弄,我传给你好了。
http://download.pudn.com/downloads55/sourcecode/windows/csharp/23825756erchapaixushu.cpp.rar

这是 另外一个:http://download.pudn.com/downloads74/sourcecode/math/39709591BSortTree.rar