二叉树的 C++ 析构函数

c++ destructor for a binary 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;
        }
    }
};

和我的节点header

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

现在一切正常,如果在 ExpressionTree class 中我只破坏了根,但我相信我正在以这种方式泄漏内存。这实际上是正确的方法还是我的递归破坏有问题。

ExpressionNode 析构函数充分清理了它的内存,因为它破坏了它的 children 充分清理了它们的内存等等。你现在正在做的是 double-freeing 节点;一次是 helper() 一次是析构函数本身。您需要做的就是销毁根节点

virtual ~ExpressionTree(){
    delete root;
}

所有children节点将通过析构函数删除。