簡體   English   中英

二叉搜索樹節點刪除

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM