编程:二叉排序树,必须实现构建,查找,插入,删除四个基本操作

简单的问题,可是我不会,还要请高手帮帮忙,马上就要答辩了啊~~辛苦了啊!... 简单的问题,可是我不会,还要请高手帮帮忙,马上就要答辩了啊~~
辛苦了啊!
展开
 我来答
百度网友f72b164
2008-05-30
知道答主
回答量:37
采纳率:0%
帮助的人:11.1万
展开全部
#include <stdio.h>
#include <malloc.h>

typedef struct BiTnode
{
int data;
struct BiTnode *lchild,*rchild;
}BiTnode,*BiTree;

BiTree search_tree(BiTree T,int keyword,BiTree *father)
{
BiTree p;
*father = NULL;
p = T;
while (p && p->data!=keyword)
{
*father = p;
if (keyword < p->data)
p = p->lchild;
else
p = p->rchild;
}
return p;
}

BiTree creat_tree(int count)
{
BiTree T,p;
int i = 1;
while (i <= count)
{
if (i == 1)
{
p = (BiTnode *)malloc(sizeof(BiTree));
if (!p)
return NULL;
T = p;
scanf("%d",&p->data);
p->lchild = p->rchild = NULL;
i++;
}
else
{
int temp;
scanf("%d",&temp);
search_tree(T,temp,&p);
if (temp < p->data)
{
p->lchild = (BiTnode *)malloc(sizeof(BiTnode));
if (!p->lchild)
return NULL;
p = p->lchild;
}
else
{
p->rchild = (BiTnode *)malloc(sizeof(BiTnode));
if (!p->rchild)
return NULL;
p = p->rchild;
}
p -> data = temp;
p -> lchild = p->rchild = NULL;
i++;
}
}
return T;
}

int insert_tree(BiTree *T,int elem)
{
BiTree s,p,father;
s = (BiTnode *)malloc(sizeof(BiTnode));
if (!s)
return -1;
s->data = elem;
s->lchild = s->rchild = NULL;
p = search_tree(*T,elem,&father);
if (!p)
return -1;
if (father == NULL)
*T = s;
else if (elem < father->data)
father->lchild = s;
else
father->rchild = s;
return 0;
}

int delete_tree(BiTree *T,int elem)
{
BiTree s,p,q,father;
p = search_tree(*T,elem,&father);
if(!p)
return -1;
if(!p->lchild)
{
if (father == NULL)
{
*T = p->rchild;
free(p);
return 0;
}
if (p == father->lchild)
father->lchild = p->rchild;
else
father->rchild = p->rchild;
free(p);
return 0;
}
else
if(!p->rchild)
{
if (father == NULL)
{
*T = p->lchild;
free(p);
return 0;
}
if (p == father->lchild)
father->lchild = p->lchild;
else
father->rchild = p->lchild;
free(p);
return 0;
}
else
{
q = p;
s = p->lchild;
while (s->rchild)
{
q = s;
s = s->rchild;
}
p->data = s->data;
if (q != p)
q->rchild = s->lchild;
else
q->lchild = s->lchild;
free(s);
return 0;
}
}

main()
{
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式