2012-04-28 99 views
0

我正在從二叉搜索樹中刪除節點,並且在此函數的while循環之後不斷收到segfault錯誤。如果可以,請幫我找出任何錯誤。C++二進制搜索刪除節點的樹錯誤

下面是函數:

void deleteNode() 
    { 
     int key; 
     nodePtr location = NULL, parent = NULL; 

     cout << "Enter account number to delete: "; 
     cin >> key; 
     cout << endl << endl; 

     bool found = searchTree(key, &location, &parent); 

     if (!found) 
     { 
     cout << "Error! Account number: " << key << " was not found." 
     << endl << endl; 
     } 
     else if (location->left != NULL && location->right != NULL) 
     { //delete node with left and right subtrees 
     nodePtr leftmost = location->right, leftmostParent = NULL; 

     while (leftmost->left != NULL) 
     { 
      leftmostParent = leftmost; 
      leftmost = leftmost->left; 
     } 

     leftmost->left = location->left; 

     if (location->right != leftmost) 
      leftmost->right = location->right; cout << "1" << endl; 

     if (parent != NULL) 
     { 
      if (parent->acctNum > location->acctNum) 
       parent->left = leftmost; 
      else 
       parent->right = leftmost; 
     } 

     leftmostParent->left = NULL; 

     delete location; 
     location = NULL; 
     } 
     else if (location->left != NULL && location->right == NULL) 
     { //delete node with only a left subtree 
     if (parent->acctNum > location->acctNum) 
      parent->left = location->left; 
     else 
      parent->right = location->left; 

     delete location; 
     location = NULL; 
     } 
     else if (location->left == NULL && location->right != NULL) 
     { //delete node with only a right subtree 
     nodePtr leftmost = location->right, leftmostParent = NULL; 

     while (leftmost->left != NULL) 
     { 
      leftmostParent = leftmost; 
      leftmost = leftmost->left; 
     } 

     leftmost->right = location->right; 
     leftmostParent->left = NULL; 

     if (parent->acctNum > location->acctNum) 
      parent->left = leftmost; 
     else 
      parent->right = leftmost; 

     delete location; 
     location = NULL; 
     } 
     else 
     { //delete a leaf node 
     if (location->acctNum > parent->acctNum) 
      parent->right = NULL; 
     else 
      parent->left = NULL; 

     delete location; 
     location = NULL; 
     } 
    } 

回答

1

我看到這裏有一個問題

nodePtr leftmost = location->right, leftmostParent = NULL; 

while (leftmost->left != NULL) 
{ 
    leftmostParent = leftmost; 
    leftmost = leftmost->left; 
} 
... 

leftmostParent->left = NULL; 

如果位置 - >右邊是一片樹葉,然後leftmostParent從未設置,仍然指向NULL;所以會segfault。

+0

這個工作,並且我忘記了在刪除以前的根時將root設置爲新的頂層節點。愚蠢的錯誤 – 2012-04-28 02:25:12