您的位置:首页 > 其它

二叉排序树

2010-09-15 22:32 127 查看
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct node
{
char key[255];
struct node *LChild,*RChild;
}BSTNode,*BSTree;

void CreatBST(BSTree root);
BSTree SearchBST(BSTree bst,char* key) ;
void InsertBST(BSTree t,char* key) ;
BSTNode * DelBST(BSTree t,char* k) ;

void print_bst(BSTree t) {
if (!t)
{
print_bst(t->LChild);
printf("/t%s/t", t->key);
print_bst(t->RChild);
}
}

const int n = 10;

/*Creat new tree*/
void CreatBST(BSTree root)
{
int i;
char key[255];
memset(key,0,sizeof(key));
for(i=1;i <=n;i++)
{
scanf("%s",key);
InsertBST(root,key);
memset(key,0,sizeof(key));

}
//return bst;
}

/*Search*/
BSTree SearchBST(BSTree bst,char* key)
{
if(!bst)
return NULL;
else
if(!strcmp(bst->key,key))
return bst;
else
if((strcmp(key,bst->key))<0)
return SearchBST(bst->LChild, key);
else
return SearchBST(bst->RChild, key);
}

/*Insert*/
void InsertBST(BSTree t, char* key)
{
if(t==NULL)
{

strcpy(t->key,key);
t->LChild=NULL;
t->RChild=NULL;
}
else
{
t=(BSTree)malloc(sizeof(BSTNode));
if(strcmp(key ,t->key)<0)
{
InsertBST(t->LChild,key);
}
else if(strcmp(key ,t->key)>0)
{
InsertBST(t->RChild,key);
}
else
{
return;
}

}
}

/*Delet*/
BSTNode * DelBST(BSTree t,char* k)
{
BSTNode *p,*f,*s,*q;
p=t;
f=NULL;
while(p)
{
if(!strcmp(p->key,k))
break;
f=p;
if(strcmp(p->key,k)>0)
p=p->LChild;
else
p=p->RChild;
}
if(p==NULL)
return t;
if(p->LChild==NULL)
{
if(f==NULL)
t=p->RChild;
else
if(f->LChild==p)
f->LChild=p->RChild;
else
f->RChild=p->LChild;
free(p);
p=NULL;
}
else
{
q=p;
s=s->LChild;
while(s->RChild)
{
q=s;
s=s->RChild;
}
if(q==p)
q->LChild=s->LChild;
else
q->RChild=s->LChild;
strcpy(p->key,s->key);
free(s);
}
return t;
}

int main()
{
BSTNode* p =NULL;
BSTNode* root = (BSTNode*)malloc(sizeof(BSTNode));

int i;
char acData[255];
int loop=1;
while(loop)
{
printf("/n/n/n");
printf(" 1.Creat/n");
printf(" 2.Search/n");
printf(" 3.Insert/n");
printf(" 4.Delete/n");
printf(" 5.Print/n");
printf(" 0.exit main/n");
scanf("%d",&i);
switch(i)
{
case 0:
{
loop=0;
break;
}
case 1:
{
CreatBST(root);
break;
}
case 2:
{
printf("Please input the data you want search./n");
scanf("%s",acData);

p = SearchBST(root,acData);
printf("%s/n",p->key);
break;
}
case 3:
{
printf("Please input the data you want insert./n");
scanf("%s",acData);
InsertBST(root,acData);
break;
}
case 4:
{
printf("Please input the data you want delete./n");
scanf("%s",acData);
root=DelBST(root,acData);
break;
}
case 5:
{
printf("/n");
if (root!=NULL)
printf("The BSTree's root is:%s/n",root->key);
print_bst(root);
break;
}
default :
break;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: