递归树遍历/分支删除的隔离错误
Segfault on Recursive Tree Traversal/Branch Deletion
我正在尝试清理树的树枝,每个节点存储一个occurrence
值 对于在构建过程中每次访问节点时,"清理"是指在两个后续节点都只有一个occurrence
之后删除分支:
因此,5->1->1->1
的一个分支将变得简单5->1
.我正在使用递归树遍历(在打印所有路径时有效(,然后使用递归删除(在销毁对象时有效(:
void tree::cleanBranch(Node *node)
{
if(!node)
return;
int cnt = 0;
int ind = 0;
// 4 possible subnodes
for(int i = 0; i < 4; i++) {
if(node->subnodes[i]) {
cnt++;
ind = i;
}
if(cnt > 1)
break;
}
// Only 1 subnode and both current and subnode have occurrence of 1
if(cnt == 1 && node->occurrences == 1 &&
node->subnodes[ind]->occurrences == 1) {
delTree(node->subnodes[ind]);
return;
}
for(int i = 0; i < 4; i++)
cleanBranch(node->subnodes[i]);
}
和删除功能:
void tree::delTree(Node* node)
{
if(node) {
for(int i = 0; i < 4; i++)
delTree(node->subnodes[i]);
delete node;
}
}
但是,它会立即出现段错误。然后我创建了一个简单的树,5->1->1
,它在第一个节点上delete
上出现段错误,该树在第三个节点上调用,但在删除之前cleanBranch()
和delTree()
检查它是否为空。
我觉得我错过了一些明显的东西,任何帮助将不胜感激。
编辑
回应Qubit:
老实说,它们真的非常简单,tree
是:
tree() { root = new Node; }
指会员Node *root
.
Node
本身有:
Node(): occurrences(0), subnodes(4)
{
for(int i = 0; i < 4; i++)
subnodes[i] = NULL;
}
其中occurrences
是ulong
,subnodes
是Node*
的vector
。
回应埃里克·阿拉帕:
我目前不是,但我会把它转移过来,给它一个裂缝。
提供的代码似乎是正确的。创建树的方式可能有问题?
假设 Node 是这样的
struct Node
{
unsigned long occurrences = 0;
vector<Node*> subnodes;
Node(): occurrences(0), subnodes(4)
{
for(int i = 0; i < 4; i++)
subnodes[i] = NULL;
}
};
树的创造是这样的
// 5->1->1->1
Node* createTree()
{
Node* root = new Node;
root->occurrences = 5;
Node* cur = root;
for (int i = 0; i < 3; ++i)
{
cur->subnodes[0] = new Node;
cur->subnodes[0]->occurrences = 1;
cur = cur->subnodes[0];
}
return root;
}
(使用您的代码样式( 清洁分支工作正常。 还要添加
node->subnodes[ind] = nullptr;
后
delTree(node->subnodes[ind]);
否则,如果您不小心在同一棵树上两次调用cleanBranch,您将获得GPF。
顺便说一句,考虑使用 unique_ptr 而不是 Node*。
更新: 节点显然应该有这样的析构函数
~Node()
{
for (int i = 0; i < subnodes.size(); ++i)
{
if (subnodes[i])
{
delete subnodes[i];
subnodes[i] = nullptr; // not nesessary with vector but =)
}
}
}
比你不必使用delTree,只是
delete node->subnodes[ind];
node->subnodes[ind] = nullptr;
相关文章:
- 从矢量中删除元素后出现隔离错误
- 在 gtest 中初始化堆栈上的引用变量的隔离错误
- 线程时访问静态映射时出现隔离错误
- 并行快速排序分区中的隔离错误
- C++多线程程序:变量定义为类成员的隔离错误
- TFLite 隔离错误,通过获取C++输入和输出
- 我只是在寻找模板,在我的书中找到了这段代码,这显示了隔离错误?
- pthread_create中错误 4 的隔离错误
- 递归树遍历/分支删除的隔离错误
- 在类模板上使用 arm gcc 编译期间的隔离错误
- 从大量文件读取时出现隔离错误
- 在PHP扩展中使用emalloc从线程时出现隔离错误
- 通过 Boost Python 在C++对象之间传递共享指针的隔离错误
- 在QT中单击菜单时出现隔离错误
- 尝试访问标头声明成员时出现隔离错误
- 搜索链表时出现隔离错误
- 模板化子类析构函数中的隔离错误
- 插件中节点.js/Nan 回调C++不频繁的隔离错误
- 将行添加到 GTKTreeView 时的隔离错误
- 找不到命令时打开的隔离错误