正如标题所说,我试图从具有2例树中删除一个节点:麻烦试图消除从树中的节点(结构)
- 的节点是没有连接到任何一个叶子
- 节点连接到另一个节点
我能够做出第二种情况下工作的功能(对我来说最困难的),但第一个(似乎容易)引起分段错误没有不管我尝试什么。
这里是结构的定义:
struct node {
int value;
struct node *sx;
struct node *dx;
};
typedef struct node *tree;
这里是执行消除操作的模块:
void destroy_node(tree Y, int elem) {
if (Y->value < elem)
destroy_node(Y->dx, elem);
if (Y->value > elem)
destroy_node(Y->sx, elem);
else { //
if (Y->sx == NULL && Y->dx == NULL) {
free(Y); <-- seg fault
Y = NULL; <-- seg fault
}
if (Y->sx != NULL && Y->dx == NULL) {
Y->value = (Y->sx)->value;
free(Y->sx);
Y->sx = NULL;
}
if (Y->sx == NULL && Y->dx != NULL) {
Y->value = (Y->dx)->value;
free(Y->dx);
Y->dx = NULL;
}
if (Y->sx != NULL && Y->dx != NULL)
printf("Can't eliminate that!\n");
}
print_everything(Y);
}
这里是main
电话:
tree Y = T;
printf("Which one you want to destroy? ");
scanf("%d", &elem);
destroy_node(Y, elem);
要编译函数我使用命令
gcc -std=gnu99 -Wall -Wextra c.c
我的环境是虚拟机的Ubuntu 17.04与股票GCC
是构建树
tree insert_node(tree T, int val) {
if (T == NULL) {
T = (tree)malloc(sizeof(struct node));
T->value = val;
T->sx = NULL;
T->dx = NULL;
} else {
if ((T->value) < (val)) {
T->dx = insert_node(T->dx, val);
}
if ((T->value) > (val)) {
T->sx = insert_node(T->sx, val);
}
}
return T;
}
在这里有主的通话EDIT 1
模块此模块
printf("How many nodes your tree will have? ");
scanf("%d", &tot);
for (int i = 0; i < tot; i++) {
printf("What is the %d° node? ", (i + 1));
scanf("%d", &val);
T = insert_node(T, val);
}
P.S.如果有关于节目我会复制粘贴整个文件
你可以添加你建树的地方吗? – atru
@atru插入了您请求的其他函数,希望它有帮助 – Allen
您忘记检查'Y'是否为空。 –