搜索一般树?函数在树的末尾停止而不是搜索下一个分支
Searching a General Tree? Function is stopping at end of tree instead of searching the next branch
我有一个通用树,其中根的子节点存储在链表中,如下所示:
class node
{
int identifier;
node *parent;
std::vector<node *> children;
我正在尝试实现一个函数,该函数将搜索树和 return 指向其 int 标识符与要搜索的键匹配的节点的指针,如果未找到匹配项,则为 nullptr。以下是我认为它应该如何工作:
- 如果当前节点->标识符==标识符,return当前节点。
- 否则,如果节点没有子节点,return nullptr.
- 遍历子项列表,对每个子项递归调用 return find(int identifier)。
- 如果找不到匹配项,return nullptr.
这是用于单元测试的树:
1-\
|-2-\
| |-3
| |-4
|
|-5-\
| |-6-\
| | |-7
| |-8
| |-9
find(1)、find(2) 和 find(3) 似乎正确执行,但是,find(4) 在节点 3 处结束,而不是在 3 处停止,返回到 2,然后尝试“4”分支。
寻求帮助,弄清楚我需要做什么才能让它转到下一个分支,而不是在分支没有更多子节点时完成。谢谢大家的观看。
代码:
node* node::find(int identifier)
{
cout << "FIND: " << identifier << endl;
cout << "this->identifier: " << this->identifier << endl;
if (this->identifier == identifier) return this;
if (this->children.empty()) return nullptr;
for (node* child : this->children) return child->find(identifier);
return nullptr;
}
检查 child return 在你 return 之前是否为 null
node* childfound;
for (node* child : this->children){
childfound = child->find(identifier);
if(childfound) return childfound;
}
我有一个通用树,其中根的子节点存储在链表中,如下所示:
class node
{
int identifier;
node *parent;
std::vector<node *> children;
我正在尝试实现一个函数,该函数将搜索树和 return 指向其 int 标识符与要搜索的键匹配的节点的指针,如果未找到匹配项,则为 nullptr。以下是我认为它应该如何工作:
- 如果当前节点->标识符==标识符,return当前节点。
- 否则,如果节点没有子节点,return nullptr.
- 遍历子项列表,对每个子项递归调用 return find(int identifier)。
- 如果找不到匹配项,return nullptr.
这是用于单元测试的树:
1-\
|-2-\
| |-3
| |-4
|
|-5-\
| |-6-\
| | |-7
| |-8
| |-9
find(1)、find(2) 和 find(3) 似乎正确执行,但是,find(4) 在节点 3 处结束,而不是在 3 处停止,返回到 2,然后尝试“4”分支。
寻求帮助,弄清楚我需要做什么才能让它转到下一个分支,而不是在分支没有更多子节点时完成。谢谢大家的观看。
代码:
node* node::find(int identifier)
{
cout << "FIND: " << identifier << endl;
cout << "this->identifier: " << this->identifier << endl;
if (this->identifier == identifier) return this;
if (this->children.empty()) return nullptr;
for (node* child : this->children) return child->find(identifier);
return nullptr;
}
检查 child return 在你 return 之前是否为 null
node* childfound;
for (node* child : this->children){
childfound = child->find(identifier);
if(childfound) return childfound;
}