检索树

再来个检索树:

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h> 
typedef  int  valuetype;  
typedef  int  element_type;
typedef   struct  Bnode   
   { element_type data;   
     struct  Bnode  *Lson, *Rson; 
    int layer,height;
} Bnode, *Bptr;  

void insert(element_type x,Bptr &p)
{
 if(p==NULL)                 
 {
  p=new Bnode;           
  p->data=x;
  p->Lson=p->Rson=NULL;  
  return;                
 }
 if(x<=p->data)insert(x,p->Lson); 
 else insert(x,p->Rson);
 } 
  
 Bptr creat()
 {
  Bptr root; element_type x;
  root=NULL;
  scanf("%d",&x);
  while(x!=0)
  {
   insert(x,root);
   scanf("%d",&x);
   } 
   return root;
 }
 
int zhongxu(Bptr p)
{
	if(p==NULL) return 0;
	zhongxu(p->Lson);
	printf("%d ",p->data);
	zhongxu(p->Rson);
}
int xianxu(Bptr p)
{
	if(p==NULL) return 0;
	printf("%d ",p->data);
	zhongxu(p->Lson);	
	zhongxu(p->Rson);
}
Bptr search(int x,Bptr p)
 {
  if(p==NULL) return NULL;
  if(x==p->data) return p;
  if(x<p->data) return search(x,p->Lson);
  else return search(x,p->Rson);
 }
 
 int deleteT(element_type x,Bptr root)
 {
  Bptr f,p,q,s,r;
  p=NULL;
  f=root;
  q=root->Rson;
  while(q!=NULL)
  if(x==q->data){
 p=q;
  q=NULL;
  }
  else if(x<q->data){
   f=q;q=q->Lson;
  }
  else{f=q;q=q->Rson;
  }
  if(p==NULL) return 0;
 if(p->Rson==NULL)
 if(p==f->Lson){
  f->Lson=p->Lson;free(p); 
 }
 else{f->Rson=p->Lson;free(p);
 }
 else
 if(p->Lson==NULL)
 if(p==f->Lson){f->Lson=p->Rson;free(p);
 } 
 else{f->Rson=p->Rson;free(p); 
 }
 else{
  s=p->Lson;
  if(s->Rson==NULL)
  {
   p->data=s->data;
   p->Lson=s->Lson;
   free(s);
  }
  else{
   r=s->Rson; 
   while(r->Rson!=NULL){
  s=r;r=r->Rson; 
  }
  p->data=r->data;
  s->Rson=r->Lson;
  free(r);
  }
}
return 1;
}
int main()  //24 14 39 21 16 32 0
{
	int i,j,t,x;
	Bptr root;
	printf("请输入元素值序列(以0结尾)\n");
	root=creat();
	printf("当前树的先序序列和中序序列为:\n");
	xianxu(root);
	printf("\n");
	zhongxu(root);
	printf("\n");
	printf("请选择要使用的功能:1、插入 2、删除 3、查找\n");
	scanf("%d",&t);
	if(t==1)
	{
		printf("请输入要插入的值:\n");
		scanf("%d",&x);
		insert(x,root);
		printf("插入后的中序序列为:\n");
		zhongxu(root);printf("\n");
	}
	if(t==2)
	{
		printf("请输入要删除的值:\n");
		scanf("%d",&x);
		deleteT(x,root);
		printf("删除后的中序序列为:\n");
		zhongxu(root);printf("\n");
	}
	if(t==3)
	{
		printf("请输入要查找的值:\n");
		scanf("%d",&x);
		search(x,root);
	}
 } 
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值