The_Coding_Is_Now
The_Coding_Is_Now

Reputation: 35

Binary Search Tree destructor c++

I'm trying to make a Binary Search Tree recursively and I had some troubles with the destructor. My BST is named BSNode based on a class using:

private:
    int _count;
    string _data;
    BSNode* _left;
    BSNode* _right;

this is my current destructor:

BSNode::~BSNode()
{
    if (this == NULL)
        return;
    else if ((this->_left == NULL) && (this->_right == NULL)){
        delete (this);
        return;
    }
    else if (this->_left == NULL)
    {
        this->_right->~BSNode();
        delete (this);
        return;
    }
    else if (this->_right == NULL)
    {
        this->_left->~BSNode();
        delete (this);
        return;
    }
    else
    {
        this->_left->~BSNode();
        this->_right->~BSNode();
        delete (this);
        return;
    }

}

I have a problem that after a while (destructing the "nodes" of the class), the program stops and when I started debugging the program , I saw that when the function reaches the end of the tree, it doesn't destory the node and keep getting the same node as if the function was called recursively with the same node. How can I fix it?

This is the error I get every time the program enters the destructor

Upvotes: 0

Views: 4246

Answers (2)

Abubakar Cool
Abubakar Cool

Reputation: 1

        ~tree()
{
    remove(root);
}
void remove(node* temp)
{
    if (temp == NULL)
        return;
    remove(temp->left);
    remove(temp->right);
    delete temp;
}

Upvotes: 0

pwilmot
pwilmot

Reputation: 596

I think you are looking for something more like this

BSNode::~BSNode()
{
    delete(_left);
    delete(_right);
}

Upvotes: 2

Related Questions