二进制搜索树析构函数c++

Binary Search Tree destructor c++

本文关键字:c++ 析构函数 搜索树 二进制      更新时间:2023-10-16

我正试图递归地创建一个二进制搜索树,但我在析构函数方面遇到了一些问题。我的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;
    }
}

我有一个问题,过了一段时间(破坏类的"节点"),程序停止了,当我开始调试程序时,我发现当函数到达树的末尾时,它不会破坏节点,并不断获得相同的节点,就好像用相同的节点递归调用函数一样。我该怎么修?

这是我每次程序进入析构函数时得到的错误

我想你正在寻找更像这个的东西

BSNode::~BSNode()
{
    delete(_left);
    delete(_right);
}
        ~tree()
{
    remove(root);
}
void remove(node* temp)
{
    if (temp == NULL)
        return;
    remove(temp->left);
    remove(temp->right);
    delete temp;
}