二叉搜索树析构函数c ++

时间:2015-11-28 08:21:57

标签: c++ binary-search-tree

我试图以递归方式创建二进制搜索树,并且我在析构函数方面遇到了一些麻烦。 我的BST基于使用以下类的类命名为BSNode:

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

这是我目前的析构函数:

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;
    }

}

我有一个问题,经过一段时间(破坏"节点"类),程序停止,当我开始调试程序时,我看到当函数到达树的末尾时它不会破坏节点并继续获得相同的节点,就像使用相同节点递归调用该函数一样。 我该如何解决?

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

2 个答案:

答案 0 :(得分:2)

我认为你正在寻找更像这样的东西

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

答案 1 :(得分:0)

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