Dmitriy Medvedev
Dmitriy Medvedev

Reputation: 1

How do I create a destructor for my AVL tree?

I have the code:

class Node
{
public:
    ~Node();
    int key;
    Node *left;
    Node *right;
    int height;
};


Node::~Node()
{
    delete this->left;
    delete this->right;
    this->left = this->right = NULL;
}

I believe that the destructor does not work correctly, without removing "root", help me how to remove my tree completely

Upvotes: 0

Views: 680

Answers (1)

bhristov
bhristov

Reputation: 3187

You want the destructor to be in your AVLtree class, not in your Node class. You should consider making a recursive helper function to do this that will use postorder traversal to delete the tree.

I hope that this is helpful. Here is a very basic example of this:

// you will not be needing a destructor for Node because it`s left and right pointers are always going to be nullptr when a Node gets created. You will only need a destructor for Node if you have another resource that you are allocating upon the creation of a Node by using the ```new``` keyword.
struct Node
{
    Node* left = nullptr;
    Node* right = nullptr;
};

class AVLtree
{
public:

    Node* root = nullptr;

    void clearTreeHelper(Node*& treeptr)
    {
        if (treeptr != nullptr)
        {
            clearTreeHelper(treeptr->left);
            clearTreeHelper(treeptr->right);
            delete treeptr;
            treeptr = nullptr;
        }
    }

    ~AVLtree()
    {
        clearTreeHelper(root);
        if (root == nullptr)
        {
            cout << "Root has been cleared!\n";
        }
    }
};

int main()
{
    {
        AVLtree a;
        a.root = new Node;
        a.root->left = new Node;
        a.root->right = new Node;
        a.root->right->left = new Node;
        a.root->right->right = new Node;
    }
}

Upvotes: 1

Related Questions