简体   繁体   English

二叉树的C ++析构函数

[英]c++ destructor for a binary tree

When i run the destructor i get a run failed and i am not sure why here is my tree header 当我运行析构函数时,运行失败,并且我不确定为什么这是我的树头

class ExpressionTree {
private:
    ExpressionNode* root;
public:
    ExpressionTree() :
    hashmap(100000),
    root(NULL) {
    };
    virtual ~ExpressionTree(){
        helper(root);
    }

    void helper(ExpressionNode *node) {
        if ( !node ) {
            return;
        } else {
            helper( node->getLeft( ) );
            helper( node->getRight( ) );
            delete node;
        }
    }
};

and my node header 和我的节点头

class ExpressionNode {
private:
    ExpressionNode* left;
    ExpressionNode* right;
    string data;
public:
    virtual ~ExpressionNode(){
        delete left;
        delete right;
    }
};

Now everything works fine if in the ExpressionTree class i only destroy the root but i believe i am leaking memory that way. 现在,如果在ExpressionTree类中我仅销毁根目录,但一切都会正常进行,但我相信我会以这种方式泄漏内存。 Is that in fact the right way or is there something wrong with my recursive destruction. 这实际上是正确的方法还是我的递归销毁有问题?

The ExpressionNode destructor adequately cleans up it's memory which because it destroys it's children which adequately clean up their memory and so on. ExpressionNode析构函数会充分清除其内存,这是因为它破坏了适当清除其内存的子级,依此类推。 What you are doing right now is double-freeing the nodes; 您现在正在做的是释放节点的双重负担。 once by helper() and once by the destructors themselves. 一次是通过helper() ,一次是通过析构函数本身。 All you need to do is destroy the root node 您需要做的就是销毁根节点

virtual ~ExpressionTree(){
    delete root;
}

all the children nodes will be deleted through the destructors. 所有子节点将通过析构函数删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM