#include
<
stdio.h
>
#include
<
stdlib.h
>

typedef
struct
snode
...
{
int data;
struct snode *left, *right;
}
BTree;
void
insert(BTree
*&
s,
int
x)
...
{
if(s == NULL)
...{
s = (BTree *)malloc(sizeof(BTree));
s->data = x;
s->left = NULL;
s->right = NULL;
}
else if(s->data == x)
return;
else if(x < s->data)
insert(s->left, x);
else
insert(s->right, x);
}

BTree
*
creat()
...
{
BTree *t = NULL;
while(1)
...{
int x;
scanf("%d", &x);
if(x == 0)
break;
else
insert(t, x);
}
return t;
}

void
preorder(BTree
*
p)
...
{
if(p != NULL)
...{
printf("%3d", p->data);
preorder(p->left);
preorder(p->right);
}
}

BTree
*
search_num(BTree
*
t,
int
x)
...
{
if(t == NULL)
return NULL;
else
...{
if(t->data == x)
return t;
else if(x < t->data)
search_num(t->left, x);
else
search_num(t->right, x);
}
}

int
main()
...
{
BTree *tree;
printf("请输入创建一个排序二叉树的数,以0结束 ");
tree = creat();
printf("先序遍历如下 ");
preorder(tree);
printf(" ");
printf("请输入要查找的数: ");
int num;
scanf("%d", &num);
BTree *test = search_num(tree, num);
if(test)
printf("找到 ");
else
printf("没找到 ");
return 0;
}
1590

被折叠的 条评论
为什么被折叠?



