I was attempting to solve the question for deleting a node in BST, and saw a strange output. In the case where node has only right child, I was trying to delete that node and return its right child. Somehow, both of the codes below gave the correct result, even though it seems to me like only code 1 should work since we’re trying to access a deleted node.
Can someone tell me why this happens?
cpp
Code 1:
Node* temp = root->right;
delete root;
return temp;
Code 2:
Node* temp = root;
delete temp;
return root->right;
>Solution :
The result of dereferencing a deleted pointer is undefined. That means anything can happen, including having a program appear to work.
There is no promise that an exception will be thrown, or that an error message will be displayed.