[英]Binary search tree node deletion
我正在实现从二进制搜索树中删除节点的功能。 该函数的原型已设置,我无法更改,这是学校的作业。 我的代码:
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;
您在使用指针时遇到问题。 如果我们具有sometype *ptr
并且我们检查该ptr是否满足我们编写的某些空间(ptr!=NULL)
。 *ptr
是值本身,例如您的structre。 阅读有关C语言中指针类型的更多信息。
您删除的逻辑是错误的
if ((* RootPtr)->LPtr == NULL) {
/* there is only right branch or none*/
tmp = RootPtr;
*RootPtr = (* RootPtr)->RPtr;
free(*tmp);
*tmp = NULL;
}
在此代码中,您将删除所需的节点,但未添加该节点的子根
if ((* RootPtr)->LPtr == NULL) {
/* there is only right branch or none*/
tmp = RootPtr;
*RootPtr = (* RootPtr)->RPtr;
free(*tmp);
*tmp = NULL;
insert(RootPtr); //insert the child node again in the tree
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.