我正在实现从二叉搜索树中删除节点的功能。 该功能的原型已设置,我无法更改它,它是一个学校作业。 我的代码:二叉搜索树节点删除
typedef struct tBSTNode {
char Key;
struct tBSTNode * LPtr;
struct tBSTNode * RPtr;
} *tBSTNodePtr;
void BSTDelete (tBSTNodePtr *RootPtr, char K) {
tBSTNodePtr *tmp;
if (*RootPtr != NULL) {
if (K < (*RootPtr)->Key)
BSTDelete(&(* RootPtr)->LPtr, K);
else if (K > (*RootPtr)->Key)
BSTDelete(&(* RootPtr)->RPtr, K);
else {
if ((* RootPtr)->LPtr == NULL) {
/* there is only right branch or none*/
tmp = RootPtr;
*RootPtr = (* RootPtr)->RPtr;
free(*tmp);
*tmp = NULL;
}
else if ((* RootPtr)->RPtr == NULL) {
/* there is only left branch or none*/
tmp = RootPtr;
*RootPtr = (* RootPtr)->LPtr;
free(*tmp);
*tmp = NULL;
}
else
/* there are both branches, but that is for another topic*/
}
}
}
此代码工作正常,以防万一在没有连接到我删除节点分支。我期望* tmp = NULL;线,我失去了我的地址到其余的分支,但另一方面,如果这条线不包括我得到一个SEGFAULT,我想弄清楚为什么。
编辑:
好的,现在我知道错误在哪里了。这是愚蠢的错误,我应该使用tBSTNodePtr tmp;而不是tBSTNodePtr * tmp;
不幸的是,我不允许调用另一个函数insert(),所以我需要使用我已经显示的代码 – skornos