您的位置:首页 > 其它

二叉查找树

2009-12-08 19:58 92 查看
[实验内容]
1、二叉查找树的建立和中序输出
2、二叉查找树的查找

【实验测试数据】
输入数据:33,88,22,55,90,11,66,99
查找:77是否存在,99是否存在

二叉查找树性质:
1 若它的左子树非空,则左子树上所有结点的值均小于它的根结点的值;
2 若它的右子树非空,则右子树上所有结点的值均大于它的根节点的值;
3 它的左、右子树也分别为二叉查找树

源程序:

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

typedef struct BSTNode
{
int key;
struct BSTNode *lchild,*rchild;
}BSTNode, *BSTree;

void InsertBST(BSTree *bst, int key);
void CreateBST(BSTree *bst);
void InOrder(BSTree *root) ;

void InsertBST(BSTree *bst, int key)
{
BSTree s;
if (*bst == NULL)
{
s=(BSTree)malloc(sizeof(BSTNode));
s-> key=key;
s->lchild=NULL;
s->rchild=NULL;
*bst=s;
}
else
if (key < (*bst)->key)
InsertBST(&((*bst)->lchild), key);
else
if (key > (*bst)->key)
InsertBST(&((*bst)->rchild), key);
}

void CreateBST(BSTree *bst)
{
int key;
*bst=NULL;
scanf("%d", &key);
while (key!=0)
{
InsertBST(bst, key);
scanf("%d", &key);
}
}

void InOrder(BSTree *root)
{
if (*root!=NULL)
{
InOrder(&(*root) ->lchild);
printf("%3d",((*root) ->key));
InOrder(&(*root) ->rchild);
}
}

void SearchBST(BSTree *bst, int x)
{
if (*bst==NULL)
printf("%d is not found",x);
else
if(x==(*bst)->key)
{
printf("%d is found",x);
exit(0);
}
else
if (x < (*bst)->key)
SearchBST(&((*bst)->lchild), x);
else
if (x > (*bst)->key)
SearchBST(&((*bst)->rchild), x);

}

void main()
{
BSTree BST;
int x,y;
CreateBST(&BST);
InOrder(&BST);
printf("\nWhich number?\n");
scanf("%d%d",&x,&y);
SearchBST(&BST,x);
printf("\n");
SearchBST(&BST,y);
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: