我正在使用二叉搜索树,并且正在尝试创建一个删除单个节点的函数。由于某种原因,某些节点不会删除(大多数似乎是具有正确节点但不是左侧的实例),但确切地说哪个节点不会删除似乎非常随意,这使得调试变得困难。偶尔我会得到错误
mov(30071,0x7fff73b1d300) malloc: *** error for object 0x7fcb2b404f40: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
Abort trap: 6
但大部分时间节点都没有删除,程序继续运行。
这是我的删除功能:
Node* Tree::deleteNode(Node *node,string title)
{
if(node == NULL){
return node;
}
else if(node->title.compare(title) > 0){
node->left = deleteNode(node->left, title);
}
else if(node->title.compare(title) < 0){
node->right = deleteNode(node->right, title);
}
else
{
//No Child
if(node->left == NULL && node->right == NULL){
if(node == node->parent->right)
{
node->parent->right = NULL;
}
else
{
node->parent->left = NULL;
}
node = NULL;
}
//One child
else if(node->left == NULL)
{
//Here is where some fail
Node *temp = node;
node = node->right;
delete temp;
}
else if(node->right == NULL)
{
Node *temp = node;
node = node->left;
delete temp;
}
else
{
Node *temp = treeMinimum(node->right);
node->title = temp->title;
node->right = deleteNode(node->right, temp->title);
}
}
return node;
}
和
Node* Tree::treeMinimum(Node *node)
{
while(node->left != NULL)
{
node = node->left;
}
return node;
}
始终是相同的节点不会删除,但结构上相同的其他节点(没有左节点,是正确的节点)删除没有问题。程序始终以50个节点的相同树开始。如果这些信息不够,我很抱歉,如果我能提供其他任何信息,请告诉我。谢谢