二叉排序树的创建与查询 C

代码:

#include<stdio.h>
#include<stdlib.h>
typedef int KeyType; 
typedef struct Node
{
    KeyType data;
    struct Node *Lchild,*Rchild;
}BTNode,*BTree;
void InsertBT(BTree *bt,KeyType k)  
{
    BTNode *s;
    if(*bt == NULL)
	{
        s=(BTree)malloc(sizeof(BTNode));
        s->data=k;
        s->Lchild=NULL;
        s->Rchild=NULL;
        *bt=s;
    }
	else
	{           
        if(k>(*bt)->data)
		{      
            InsertBT(&((*bt)->Rchild),k);
        }
		else if(k<(*bt)->data)
		{
            InsertBT(&((*bt)->Lchild),k);
        }
    }
}
void Create(BTree *bt)
{
    KeyType key;
    *bt=NULL;
    printf("(请注意序列以 -1 为结束标志噢)\n");
    scanf("%d",&key);
    while(key!=-1)
	{
        InsertBT(bt,key);
        scanf("%d",&key);
    }
}
void Preorder(BTree bt)
{
    if(bt!=NULL)
	{
        printf("%d ",bt->data);
		Preorder(bt->Lchild);    
        Preorder(bt->Rchild);
    }
}
int count=0;
int SerchBT(BTree bt,KeyType k)
{
    BTNode *q;
    q=bt;
    if(q==NULL)
    return 0;
    else
    {
    while(q)
	{
    	count++;
        if(q->data ==k)
		{
        return count;
        }
        if(k>q->data)
		{
            q=q->Rchild;
        }
		else
		{
            q=q->Lchild;
        }
    }
    }
}
int main()
{
    int key;
	BTree bt;
    BTNode *q;
    printf("请输入数字序列:\n");
    Create(&bt);
    printf("它的先序序列为:\n");
    Preorder(bt);   
    printf("\n");
    printf("请输入查找的数字:\n");
    scanf("%d",&key);
    count=SerchBT(bt,key);
    printf("需要比较次数为%d次\n",count);
    return 0;
}

图片:

猜你喜欢

转载自blog.csdn.net/Tjhfsghbjknjdy/article/details/85012569