Akın Yılmaz Akın Yılmaz - 1 year ago 91
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)
delete p;

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 Source

use this instead :

void ProductCategory::deleteRightChild(ProductNode * p) 
        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.