求助大佬,不知道这个删除函数是什么问题
c语言吧
全部回复
仅看楼主
level 7
GHFRTDRT 楼主
其他的函数都没问题,就删除函数一用就出问题,搞不懂为什么?(代码放评论区)
2024年02月17日 08点02分 1
level 7
GHFRTDRT 楼主
#include<stdio.h>
#include<stdlib.h>
struct Tree* makeempty(struct Tree* t);//1
struct Tree* find(int x, struct Tree* t);//2
struct Tree* findmin(struct Tree* t);//3
struct Tree* findmax(struct Tree* t);//4
struct Tree* insert(int x, struct Tree* t);//5
struct Tree* Delete(int x, struct Tree* t);//6
void printtree(struct Tree* t);//中序打印 7
struct Tree
{
int element;
struct Tree* left;
struct Tree* right;
};
int main(void)
{
struct Tree* min;
struct Tree* max;
struct Tree* node;
struct Tree* root;
root = insert(6, NULL);
for (int i = 0; i < 6; i++)
{
insert(i, root);
}
printtree(root);
node = find(4, root);
printf("find node is:%d\n", node->element);
min = findmin(root);
printf("min is:%d\n", min->element);
max = findmax(root);
printf("max is:%d\n", max->element);
Delete(4, root);
printtree(root);
return 0;
}
2024年02月17日 08点02分 3
这是主函数
2024年02月17日 08点02分
level 7
GHFRTDRT 楼主
struct Tree* makeempty(struct Tree* t)//1
{
if (t != NULL)
{
makeempty(t->left);
makeempty(t->right);
free(t);
}
return NULL;
}
struct Tree* find(int x, struct Tree* t)//2
{
if (t== NULL)
{
return NULL;
}
if (x < t->element)
{
return find(x, t->left);
}
else if (x > t->element)
{
return find(x, t->right);
}
else
{
return t;
}
}
struct Tree* findmin(struct Tree* t)//3
{
if (t == NULL)
{
return NULL;
}
else if (t->left == NULL)
{
return t;
}
else
{
return findmin(t->left);
}
}
struct Tree* findmax(struct Tree* t)//4
{
if (t != NULL)
{
while (t->right != NULL)
{
t = t->right;
}
}
return t;
}
struct Tree* insert(int x, struct Tree* t)//5
{
if (t == NULL)
{
t = (struct Tree*)malloc(sizeof(struct Tree));
if (t == NULL)
{
printf("Out of space!\n");
return NULL;
}
else
{
t->element = x;
t->left = NULL;
t->right = NULL;
}
}
else if (x < t->element)
{
t->left = insert(x, t->left);
}
else if (x > t->element)
{
t->right = insert(x, t->right);
}
return t;
}
struct Tree* Delete(int x, struct Tree* t)//6删除
{
struct Tree* tmp;
if (t == NULL)
{
printf("element not found!\n");
return NULL;
}
else if (x < t->element)
{
t->left = Delete(x, t->left);
}
else if (x > t->element)
{
t->right = Delete(x, t->left);
}
else if (t->left != NULL && t->right != NULL)
{
tmp = findmin(t->right);
t->element = tmp->element;
t->right = Delete(t->element, t->right);
}
else
{
tmp = t;
if (t->left == NULL)
{
t = t->right;
}
else if (t->right == NULL)
{
t = t->left;
}
free(tmp);
}
return t;
}
void printtree(struct Tree* t)//7
{
if (t == NULL)
{
printf("Empty tree!\n");
return;
}
if (t->left != NULL)
{
printtree(t->left);
}
printf("element is: %d\n", t->element);
if (t->right != NULL)
{
printtree(t->right);
}
}
2024年02月17日 08点02分 4
level 9
无头双链表吗
2024年02月17日 08点02分 5
题目不贴出来吗[汗]
2024年02月17日 08点02分
@为什么学C 啊,没题目,只是刚学完二叉树 ,想试着实现一下
2024年02月17日 09点02分
@为什么学C sorry,忘记说了
2024年02月17日 09点02分
@为什么学C 就是二叉树根的创建,然后后续的插入和删除
2024年02月17日 09点02分
level 12
这里错了,t->right而不是left
2024年02月17日 12点02分 6
1