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