初稿,后面再完善
执行成功
#include <stdio.h>
#include <stdlib.h>
typedef struct BiTNode{
char data;
struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
//插入
void insert(BiTree *t, int key)
{
if(*t == NULL)
{
(*t) = (BiTree)malloc(sizeof(BiTNode));
(*t)->data = key;
(*t)->lchild = (*t)->rchild = NULL;
}
else{
if(key == (*t)->data)
{
printf("该数已存在\n");
return ;
}
else if(key < (*t)->data)
insert(&((*t)->lchild), key);
else if(key > (*t)->data)
insert(&((*t)->rchild), key);
}
}
//查找
BiTree search(BiTree t, int key)
{
if(t)
{
if(key == t->data)
return t;
else if(key < t->data)
return search(t->lchild, key);
else if(key > t->data)
return search(t->rchild, key);
}
return NULL;
}
void print(BiTree t) //中序排序 按大小
{
if(t)
{
print(t->lchild);
printf("%d ", t->data);
print(t->rchild);
}
}
//删除
void delete(BiTree *t)
{
BiTree pre, s;
if((*t)->lchild == NULL) //左子树为空
{
pre = *t;
*t = (*t)->rchild;
free(pre);
pre = NULL;
}
else if((*t)->rchild == NULL) //左子树为空
{
pre = *t;
*t = (*t)->lchild;
free(pre);
pre = NULL;
}
else{
pre = (*t)->lchild;
s = (*t)->lchild;
while(s->rchild)
{
pre = s;
s = s->rchild;
}
(*t)->data = s->data;
if(pre != s)
pre->rchild = s->lchild;
else
(*t)->lchild = s->lchild;
free(s);
pre = NULL;
}
}
int delete_bst(BiTree *t, int key)
{
if(!(*t))
{
printf("未找到\n");
return 0;
}
else{
if(key == (*t)->data)
delete(t);
else if(key < (*t)->data)
delete_bst(&((*t)->lchild), key);
else if(key > (*t)->data)
delete_bst(&((*t)->rchild), key);
}
}
int main()
{
BiTree t=NULL, p=NULL;
int key, mode;
while(1)
{
printf("1 插入, 2 查找, 3 中序遍历, 4删除\n");
scanf("%d", &mode);
switch(mode)
{
case 1:
printf("请输入要插入数:");
scanf("%d", &key);
insert(&t, key);
break;
case 2:
if(t == NULL)
printf("树为空\n");
else
{
printf("请输入查找的数:");
scanf("%d", &key);
p = search(t, key);
if(p)
printf("查找成功\n");
else
printf("查找失败\n");
}
break;
case 3:
if(t == NULL)
printf("树为空\n");
else
{
printf("中序遍历:");
print(t);
printf("\n");
}
break;
case 4:
printf("请输入删除的数:");
scanf("%d", &key);
delete_bst(&t, key);
break;
}
}
return 0;
}