Akın Yılmaz Akın Yılmaz - 1 month ago 17
C++ Question

c++ delete in binary search tree

I have a binary search tree consists of nodes like:

struct ProductNode
{
Product data;
ProductNode* left;
ProductNode* right;
};


and I have a delete function that takes ProductNode pointer parameter:

void ProductCategory::deleteandnull(ProductNode * p)
{
if(p!=NULL)
{
delete p;
p=NULL;
}
}


I have no problem with deletion methods. The left and right pointers are NULL when a new leaf added but when I use this function I see there is no deletion and this operation does not change the binary search tree. What is that problem?

Answer

use this instead :

void ProductCategory::deleteRightChild(ProductNode * p) 
{
    if(p->right!=NULL)
    {
        delete p->right;
        p->right = NULL;
    }
}

write an equivalent fonction for left child.

your function does not work because you dont change the content of the parent node. it still has the adress of the deleted node so (if this content was realllocated elsewhere and changed) it can access to it... !

but the memory is really deallocated.

Comments