#include <stdio.h>
#define ENDKEY 0
typedef struct node
{
int key;
struct node *lchild,*rchild;
}BSTNode,*BSTree;
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;
printf("shuru 0 shi jieshu/n");
scanf("%d",&key);
while(key!=ENDKEY)
{
InsertBST(bst,key);
scanf("%d",&key);
}
}
void SearchBST(BSTree *bst,int key)
{
int n=1;
BSTree *q;
q=bst;
while(q)
{
if(key==(*q)->key)
printf("%d/n",n);
if(key<(*q)->key)
q=&((*q)->lchild);
else q=&((*q)->rchild);
n++;
}
}
void display(BSTree *tr)
{
if(*tr!=NULL)
{
printf("%d/t",(*tr)->key);
display(&((*tr)->lchild));
display(&((*tr)->rchild));
}
}
void main()
{
BSTree *tree;
int a;
CreateBST(tree);
display(tree);
printf("please input a number/n");
scanf("%d",&a);
printf("gai shu zai d cengshu shi:");
SearchBST(tree,a);
}
求出指定结点在给定二叉排序树中所在的层数
最新推荐文章于 2022-10-07 18:02:53 发布