Generic binary tree node destructor issue

淺唱寂寞╮ 提交于 2019-12-06 09:25:38

Your BinTreeNode destructor should simply be:

template <class T>
BinTreeNode<T>::~BinTreeNode() {
    delete left;
    delete right;
}

That will call left and right's destructors recursively, freeing the memory allocated for those nodes and their child nodes. This will as a consequence free the entire tree.

Assigning NULL to a pointer does not free the memory pointed by it.

On the other hand, what you mention, that after deletion, this line:

node->getData();

Still returns data, is perfectly normal. Deletion frees the memory, but the data stored in it might still be available for a while, until something new is written in that memory address. Accessing an already free'd memory address implies undefined behaviour.

BTW, you should use "0"(without quotes) in C++ instead of NULL. Therefore, there it's not necessary to use the #ifndef NULL(...).

EDIT: I hadn't seen the "no recursion" comment. Here's a non-recursive algorithm:

#include <deque>

/* ... */

template <class T>
BinTreeNode<T>::~BinTreeNode() {
    std::deque deq;
    // we're going to delete our children
    deq.push_back(this);
    while(deq.size()) {
        BinTreeNode<T> *ptr = deq.front();
        deq.pop_front();
        if(ptr) {
            deq.push_back(ptr->left);
            deq.push_back(ptr->right);
            // we don't want the child nodes
            // to double delete the children
            ptr->left = 0;
            ptr->right = 0;
            // avoid deleteing ourselves
            if(ptr != this)
                delete ptr;
        }
    }
}

I haven't tested it, but it should work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!