我正在从二进制搜索树中删除节点,并且在此函数中的while循环后我不断收到段错误。如果可以,请帮助我发现任何错误。
这是功能:
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;
}
}
答案 0 :(得分:1)
我在这里看到一个问题
nodePtr leftmost = location->right, leftmostParent = NULL;
while (leftmost->left != NULL)
{
leftmostParent = leftmost;
leftmost = leftmost->left;
}
...
leftmostParent->left = NULL;
如果location-&gt; right是一个叶子,那么leftmostParent永远不会被设置并且仍然指向NULL; segfault也是如此。