簡體   English   中英

二進制搜索樹析構函數c ++

[英]Binary Search Tree destructor c++

我試圖遞歸地制作二進制搜索樹,而析構函數遇到了一些麻煩。 我的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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM