这应该是遍历一个BST并删除每个节点,包括根节点。然而,最后,我得到了“root还有一个左节点”的消息。为什么并非所有节点都被删除?为什么我的C++代码无法删除BST中的所有节点?
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;
}
为什么当它检查正确的节点时,它找不到任何东西,但是当它检查左节点时它找到了什么? – neuromancer 2010-02-11 03:14:51
因为'root'只是指向垃圾内存。其他结果可能包括只剩下,既不,也不会崩溃。 – Potatoswatter 2010-02-11 03:44:43