我的二叉树删除功能有问题,特别是两个子案例。 我的删除代码如下所示,名为with-in
的相关函数treeNode* delete(treeNode* root, treeNode* del)
{
treeNode *tempLeft; //node left of curr
treeNode *tempRight; //node right of curr
treeNode *save_node;
treeNode *par;
par = parent(root, del); // Get the parent of this node.
// Take care of the case where the node to delete is a leaf node.
if (isLeaf(del))
{
// Deleting the only node in the tree.
if (par == NULL)
{
free(root); // free the memory for the node.
return NULL;
}
// Deletes the node if it's a left child.
if (compareDates(par->people, del->people) > 0)
{
free(par->left); // Free the memory for the node.
par->left = NULL;
}
// Deletes the node if it's a right child.
else
{
free(par->right); // Free the memory for the node.
par->right = NULL;
}
return root; // Return the root of the new tree.
}
if (hasOnlyLeftChild(del))
{
// Deleting the root node of the tree.
if (par == NULL)
{
save_node = del->left;
save_node->top = 1;
free(del); // Free the node to delete.
return save_node; // Return the new root node of the resulting tree.
}
// Deletes the node if it's a left child.
if (compareDates(par->people, del->people) > 0)
{
save_node = par->left; // Save the node to delete.
par->left = save_node->left; // Readjust the parent pointer.
free(save_node); // Free the memory for the deleted node.
}
// Deletes the node if it's a right child.
else
{
save_node = par->right; // Save the node to delete.
par->right = save_node->left; // Readjust the parent pointer.
free(save_node); // Free the memory for the deleted node.
}
return root; // Return the root of the tree after the deletion.
}
// Takes care of the case where the deleted node only has a right child.
if (hasOnlyRightChild(del))
{
// Node to delete is the root node.
if (par == NULL)
{
save_node = del->right;
save_node->top = 1;
free(del);
return save_node;
}
// Delete's the node if it is a left child.
if (compareDates(par->people, del->people) > 0)
{
save_node = par->left;
par->left = save_node->right;
free(save_node);
}
// Delete's the node if it is a right child.
else
{
save_node = par->right;
par->right = save_node->right;
free(save_node);
}
return root;
}
if(hasTwoChildren(del))
{
treeNode *temp;
save_node = del->left;
save_node = maxVal(save_node);
temp = save_node;
delete(root,save_node);
del->people = temp->people;
free(temp);
}
}
使用两个子案例我在左子树副本中找到最大值到temp var然后在save_node上调用delete然后用temps数据覆盖del中的数据,这样我就不必担心删除一个有两个孩子的节点并修复指针。在我看来应该工作。我遇到的问题是,当我在save_node上运行delete时,它也正在删除我创建的temp,所以当我去复制temp-> people in del-> people时,它的NULL为NULL但是我从不触摸temp delete在save_node上运行。
这是一个记忆错误吗,我是自由还是写到记忆中我没有让我得到这个奇怪的结果?是我的删除代码是正确的,我导致错误发生在我的代码的另一部分的问题吗?我是如此坚持这样一个事实:我认为逻辑是对的,我不能让自己去看问题
答案 0 :(得分:0)
如果我理解正确,temp
和save_node
在有两个孩子的情况下指向相同的地址。
因此,当您稍后释放此地址时,temp
和save_node
都会被释放。