2012-04-28 22 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を指しています。セグメンテーションもそうです。

+0

これはうまくいきました。以前のルートを削除するときに、新しいトップノードにrootを設定するのを忘れてしまいました。愚かな間違い –

関連する問題