这应该遍历 BST 并删除每个节点,包括根节点。但是,最后,我收到消息“root 仍然有一个左节点”。为什么没有删除所有节点?
void deleteTree()
{
deleteNode(root);
if(root->right)
cout << "root still has a right node" << endl;
if(root->left)
cout << "root still has a left node" << endl;
root = 0;
}
void deleteNode(node *p)
{
if(p->left)
{
deleteNode(p->left);
p->left = 0;
}
if(p->right)
{
deleteNode(p->right);
p->right = 0;
}
cout << "Deleting node containing " << p->data << endl;
delete p;
}
最佳答案
您正在删除末尾的 p
(root
),然后尝试在 deleteTree()
中访问其内容,其中 root
不再指向分配的内存。结果将是不确定的。
关于c++ - 为什么我的 C++ 代码无法删除 BST 中的所有节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2241949/