#include<stdio.h>
#include<stdlib.h>
typedef int type;
typedef struct lnode
{
type key;
struct lnode *lchild ,*rchild;
}node ,*ntree;
void insertbst(ntree *bstree,type k)
{
if(bstree==NULL)
{
ntree p;
p=(ntree)malloc(sizeof(node)) ;
p->key=k;
p->lchild=p->rchild=NULL;
*bstree=p;
//printf("%d ",p->key);
//printf("%d ",s->key);
//printf("111%d ",bstree->key);
}
else if(k<(*bstree)->key) insertbst((&(*bstree)->lchild),k);
else if(k>(*bstree)->key) insertbst((&(*bstree)->rchild),k);
}
void createbstree(ntree *bstree)
{
type key;
bstree=NULL;
scanf("%d",&key);
int i=0;
while(key!=-32767)
{
insertbst(bstree,key);
scanf("%d",&key) ;
}
}
node *searchbst1(node *bst,type key)
{
if(bst==NULL)
return bst;
else if(key==bst->key) return bst;
else if(key<bst->key) searchbst1(bst->lchild,key);
else searchbst1(bst->rchild,key);
}
node *searchbst2(ntree bst,type n)
{
ntree s=bst;
// printf("%%%55 ");
while(s!=NULL)
{printf("jin%d ");
printf("%d ",s->key);
if(n<s->key)
s=s->lchild;
if(n>s->key)
s=s->rchild;
if(n==s->key)
return s;
}
return NULL;
}
void preorder_traversal(node *t)
{
if (t == NULL)
return;
else
{
printf("%d ",t->key);
preorder_traversal(t->lchild);
preorder_traversal(t->rchild);
}
}
int main(void)
{
ntree *bstree;
node *s;
type n;
printf("请输入一组值\n");
createbstree(bstree);
printf("先序遍历:\n");
preorder_traversal(*bstree);
printf("请输入要查找的值\n");
scanf("%d",&n);
// printf("递归查找:\n") ;
//(s=searchbst1(bstree,n))==NULL ?printf("未找到\n"):printf("找到%d\n",s->key);
printf("非递归查找:\n") ;
// (s=searchbst2(*bstree,n))==NULL ?printf("未找到\n"):printf("找到%d\n",s->key);
}
二叉查找树的创建插入删除遍历的递归实现与非递归C语言实现
最新推荐文章于 2019-08-11 17:42:14 发布