二进制搜索树节点删除

时间:2012-11-05 08:42:47

标签: c binary-search-tree nodes

我正在实现从二叉搜索树中删除节点的功能。 该功能的原型已设置,我无法更改它,这是一项学校作业。 我的代码:

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;

2 个答案:

答案 0 :(得分:1)

使用指针时遇到问题。如果我们有sometype *ptr,我们会检查此ptr是否在某个空间中写入(ptr!=NULL)*ptr正在引用值本身,例如引用您的structre。 阅读有关C中指针类型的更多信息。

答案 1 :(得分:0)

您的删除逻辑错误

 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
            }