【发布时间】:2014-09-12 21:36:34
【问题描述】:
我正在为 C++ 赋值编写代码,它是使用二叉搜索树的字典实现。我的代码可以编译,但是当我尝试“删除”时,我得到了一个段错误。任何想法为什么会发生。谢谢
这是我的代码
// this function calls the deleteNode function where the deletion is done
void BST::deleteContent(string *word)
{
deleteNode(word, root);
}
// a helper fuuntion for the deletecontent function
//uses recursion to find the node to be deleted
void BST::deleteNode(const string *word, Node *&nodePtr)
{
if(word < nodePtr->word)
deleteNode(word, nodePtr->left);
else if(word > nodePtr->word)
deleteNode(word, nodePtr->right);
else
makeDeletion(nodePtr);
}
// a helper function for the deleteNode function
void BST::makeDeletion(Node *&nodePtr)
{
Node *tempNodePtr;
if(nodePtr == NULL)
cout<< "cannot delete empty node. \n";
// if node has no right child
else if (nodePtr->right == NULL)
{
tempNodePtr = nodePtr;
nodePtr = nodePtr->left; // reattach child
delete tempNodePtr;
}
else if(nodePtr-> left == NULL)
{
tempNodePtr = nodePtr;
nodePtr = nodePtr->right; // reattach child
delete tempNodePtr;
}
// if node has 2 children
else
{
tempNodePtr = nodePtr->right;
while (tempNodePtr->left)
tempNodePtr = tempNodePtr->left;
tempNodePtr->left = nodePtr->left;
tempNodePtr = nodePtr;
nodePtr = nodePtr->right;
delete tempNodePtr;
}
}
编辑:
谢谢大家!!从您的帖子中,我意识到检查节点是否是最后一个并且没有子节点是个好主意。我在 deleteNode 中添加了这个检查
if((nodePtr->left) && word < nodePtr->word)
{
do something
}
我对右边做了同样的事情 它工作并且没有抛出任何错误或段错误。非常感谢!!!!
【问题讨论】:
-
如果被删除的单词不在树中,你将递归到一个空节点。然后,当您尝试执行
nodePtr->word时,您将取消对空指针的引用。 -
启用 coredump 并查看回溯。在删除检查 null 和打印输出之前
-
在
makeDeletion中,您不处理左右孩子都为空的情况。 -
几乎需要重写整个
makeDeletion方法。并首先说明您希望它做什么,这样我们就清楚了。 -
最重要的编程技能之一是调试艺术。这是学习如何做到这一点的主要候选者——尝试单步执行代码,确保每一步都按照您期望的方式执行(并且变量的值是您认为它们应该是的值)。当您发现您的心智模型与实际发生的情况不匹配时,很可能就是代码中的错误所在(或者至少,比最终导致的分段错误更接近该点)。
标签: c++ dictionary binary-search-tree