简体   繁体   English

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

[英]Binary Search Tree destructor c++

I'm trying to make a Binary Search Tree recursively and I had some troubles with the destructor. 我试图递归地制作二进制搜索树,而析构函数遇到了一些麻烦。 My BST is named BSNode based on a class using: 我的BST使用以下类基于一个类命名为BSNode:

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

this is my current destructor: 这是我当前的析构函数:

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

}

I have a problem that after a while (destructing the "nodes" of the class), the program stops and when I started debugging the program , I saw that when the function reaches the end of the tree, it doesn't destory the node and keep getting the same node as if the function was called recursively with the same node. 我有一个问题,过了一会儿(破坏了类的“节点”),程序停止了,当我开始调试程序时,我发现当函数到达树的末尾时,它并不会破坏节点并保持获得相同的节点,就好像该函数是用相同的节点递归调用的一样。 How can I fix it? 我该如何解决?

This is the error I get every time the program enters the destructor 这是我每次程序进入析构函数时都会遇到的错误

I think you are looking for something more like this 我认为您正在寻找更像这样的东西

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

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

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