二叉排序树(插入、删除、查找)

#include<stdio.h>
#include<stdlib.h>
typedef struct elem{
  int key;
}elem;
typedef struct node{
   elem data;
   struct node* lchild,*rchild;
}*Bitree,Binode;
int Search(Bitree T,int key)
{
	if (!T)
	{
		printf("查找失败\n");
		return 0;
	}
	else
	{
	if (T->data.key==key)
	{
		printf("查找成功\n");
	  return 1;
	}
	else if (T->data.key<key)
		Search(T->rchild,key);
	else
		Search(T->lchild,key);
	}
	return 0;
}

void Insert(Bitree &T,int data)
{
	Bitree s;
	if (!T)
	{
	   s=(Bitree)malloc(sizeof(Binode));
	   s->data.key=data;
	   s->lchild=s->rchild=NULL;
	   T=s;
	}
	else  if (T->data.key<data)
		Insert(T->rchild,data);
	else
		Insert(T->lchild,data);
}

void Dele(Bitree &T,int key)
{
	Bitree pre,p,q;
     p=T;
	 while (p&&p->data.key!=key)
	 {
	     if (p->data.key<key)
		 {
		    pre=p;
			p=p->rchild;
		 }
		 else
		 {
		    pre=p;
			p=p->lchild;
		 }
	 }
	 if (!p)
	 {
	    printf("无此值\n");
		return;
	 }
	 if (!p->lchild)		//左子树为空
	 {
	     if (p==T)
			 T=T->rchild;
		 else if (pre->rchild==p)
		      pre->rchild=p->rchild;
			else 
				pre->lchild=p->rchild;
			free(p);
	 }
	 else  if (!p->rchild)		//右子树为空
	 {
		 if (p==T)
			  T=T->lchild;
		 else if (pre->lchild==p)	
			pre->lchild=p->lchild;
		else
			pre->rchild=p->lchild;
		free(p);
	 }
	 else				//不用判断删除根结点
	 {
		 pre=p;
		q=p->lchild;
	     while (q->rchild)
		 {
		    pre=q;
			q=q->rchild;
		 }
		 p->data.key=q->data.key;
		 if (pre!=p)
			 pre->rchild=q->lchild;
		 else
			 pre->lchild=q->lchild;
		 free(q);
	 }
}
void Preorder(Bitree T)
{
	if (T)
	{
	  printf("%d ",T->data.key);
	  Preorder(T->lchild);
	  Preorder(T->rchild);
	}
}
void Inorder(Bitree T)
{
   if (T)
   {
	  Inorder(T->lchild);   
	   printf("%d ",T->data.key);
	   Inorder(T->rchild);
   }
}
void Creat(Bitree &T)
{
	int data;
    T=(Bitree)malloc(sizeof(Binode));
	T=NULL;
	scanf("%d",&data);
	while (data)
	{
	    Insert(T,data);
	    scanf("%d",&data);
	}
}
int main()
{
	int a,data;
	Bitree T;
	printf("建树,输入0结束:\n");
	Creat(T);
	printf("\n");
	while (1)
	{
		printf("选择操作:\n1.查找\n2.插入结点\n3.删除节点\n4.前序遍历输出\n5.中序遍历输出\n6.退出\n\n");
		scanf("%d",&a);
	switch (a)
	{
	case 1:{
		      printf("输入要查找的值:\n");
		      scanf("%d",&data);
		      Search(T,data);
			  break;
		   }
	case 2:{
		      printf("输入要插入的结点:\n");
			  scanf("%d",&data);
		      Insert(T,data);
			  break;
		   }
	case 3:
		{	
			printf("输入要删除的结点:\n");	
		     scanf("%d",&data);
			 Dele(T,data);
			 break;
		}
	case 4: {
			   Preorder(T);
			   printf("\n");
			   break;
			}
	case 5: {
			  Inorder(T);
			  printf("\n");
			  break;
			}
	case 6: return 0;
	}//switch
	}//while
	return 0;
}

你可能感兴趣的:(二叉排序树(插入、删除、查找))