双删除(?)在二叉搜索树中
Double Delete(?) In Binary Search Trees
我正在写一个代码,测试两个二叉搜索树是否相等。
然而,每当我释放内存时,我就会遇到访问冲突错误。通过它,我看到我正在访问内存地址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==
来比较两个对象。
相关文章:
- 删除二叉搜索树 (C++) 中的单个元素
- 二叉搜索树 - 使用 Linux 在虚拟机中制作删除功能
- 删除节点方法实际上不会删除二叉搜索树中的节点.C++
- C++ 从二叉搜索树中删除具有两个子节点的特定节点
- 在二进制搜索树中删除节点
- 如何从二进制搜索树中删除节点
- 从C++二进制搜索树中删除一个节点(类而非结构)
- 从基于矢量的二叉搜索树中删除节点的最佳方法
- C++ 通过无序变量删除二叉搜索树
- 二叉搜索树删除 (C++)
- 二叉搜索树查找和删除 [C++]
- 无法从二进制搜索树中删除叶子
- 二进制搜索树删除而无需复制
- 二进制搜索树 - 删除节点,没有指向前任的指针
- 二进制搜索树C删除节点一些错误
- C++二进制搜索树删除问题
- C++二进制搜索树删除分段错误
- 二进制搜索树删除两个子
- 二进制搜索树--删除函数不起作用
- 二叉搜索树删除方法