双删除(?)在二叉搜索树中

Double Delete(?) In Binary Search Trees

本文关键字:搜索树 删除      更新时间:2023-10-16

我正在写一个代码,测试两个二叉搜索树是否相等。

然而,每当我释放内存时,我就会遇到访问冲突错误。通过它,我看到我正在访问内存地址0xfee在我的释放函数上。我在Cell析构函数中得到访问冲突。

我也真的不知道这个功能是否有效,但是我并不是真的在寻求帮助——尽管帮助仍然会很感激。

回收功能:

~Cell(void) {
    if (left) { delete left; }
    if (right) { delete right; }
}

功能:

bool BST::isEqualTo(const BST& that) const{
    if(root <= 0 && that.root <= 0){
        return true;
    }else if(root <= 0 || that.root <= 0){
        return false;
    }
    if(root->val != that.root->val){
        false;
    }
    /*Cell* saved_node1 = new Cell(*root);
    Cell* saved_node2 = new Cell(*that.root);*/
    BST a, b, c, d;
    a.root = root->left;
    b.root = that.root->left;
    c.root = root->right;
    d.root = that.root->right;
    if(a.isEqualTo(b) && c.isEqualTo(d)){
        /*a.root = saved_node1;
        b.root = saved_node2;
        c.root = saved_node1;
        d.root = saved_node2;*/
        return true;
    }
    return false;
}

树析构函数:

void BST::destroy(void) {
    length = 0;
    delete root;
    root = nullptr;
}

那么,在这部分代码中

BST a, b, c, d;
a.root = root->left;
b.root = that.root->left;
c.root = root->right;
d.root = that.root->right;

创建BST对象,该对象将在函数完成后立即销毁。在此之后,分配给root指针的所有内存将被释放。

我建议你写另一个比较函数,像这样:

bool _is_equal(Cell* c1, Cell* c2)
{
    if(c1 == nullptr && c2 == nullptr)
        return true;
    else if(c1 == nullptr || c2 == nullptr)
        return false;
    return  (c1 -> val == c2 -> val) &&
            _is_equal(c1 -> left,  c2 -> left) &&
            _is_equal(c1 -> right, c2 -> right);
}
并在函数 中调用它
bool BST::isEqualTo(const BST& that) const
{
    return _is_equal(root, that.root);
}

当然,你应该重载operator==来比较两个对象。