递归树遍历/分支删除的隔离错误

Segfault on Recursive Tree Traversal/Branch Deletion

本文关键字:隔离 错误 删除 分支 遍历 递归      更新时间:2023-10-16

我正在尝试清理的树枝,每个节点存储一个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;
}

其中occurrencesulongsubnodesNode*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;