Consider the following function which erases a node from a binary search tree if the node has no children:
void erase_no_children(node* todel)
{
//...
if (todel->parent->left == todel) //if todel is left child
todel->parent->left = nullptr;
if (todel->parent->right == todel) //if todel is right child
todel->parent->right = nullptr;
delete todel;
}
Since todel->parent->left == todel
that means that by setting todel->parent->left
to nullptr
, I'm just as well setting todel
to nullptr
. The compiler doesn't complain at all.
Question: Is this safe to do? Does it leak? Or is it undefined behaviour?