This is supposed to traverse a BST and delete every node, including the root node. However, at the end, I get the message “root still has a left node.” Why aren’t all nodes deleted?
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;
}
Your are deleting
pat the end (root) and then trying to access its contents indeleteTree(), whererootno longer points to allocated memory. The result is going to be undefined.