2012-04-28 1 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

이 작업은 이전 루트를 삭제할 때 루트를 새 최상위 노드로 설정하는 것을 잊어 버렸습니다. 멍청한 실수 –

관련 문제