【问题标题】:Searching a General Tree? Function is stopping at end of tree instead of searching the next branch搜索一般树?函数在树的末尾停止而不是搜索下一个分支
【发布时间】:2021-09-15 07:47:19
【问题描述】:

我有一个通用树,其中根的孩子存储在一个链表中,如下所示:

class node
{
    int identifier;
    node *parent;
    std::vector<node *> children;

我正在尝试实现一个函数,该函数将搜索树并返回指向其 int 标识符与要搜索的键匹配的节点的指针,如果未找到匹配项,则返回 nullptr。以下是我认为它应该如何工作:

  1. 如果当前节点->标识符==标识符,则返回当前节点。
  2. 否则,如果节点没有子节点,则返回 nullptr。
  3. 遍历子列表,递归调用并返回每个子的 find(int identifier)。
  4. 如果未找到匹配项,则返回 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;
}

【问题讨论】:

  • 在返回之前检查孩子是否返回null
  • 我相信使用队列的广度优先搜索比您的代码执行递归深度优先搜索更容易且堆栈密集度更少。
  • 谢谢亚伯! PaulMcKenzie,你绝对是对的,但我已经接近到期日,只需要在我提高效率之前获得最小的可行产品。感谢您提及。
  • @WilliamSchaffer See this。这构建了您说明的树,并使用简单的广度优先搜索找到了 4。

标签: c++ c++11 recursion data-structures tree


【解决方案1】:

在返回之前检查孩子是否返回 null

node* childfound;
for (node* child : this->children){
childfound = child->find(identifier);
if(childfound) return childfound;
}

【讨论】:

    猜你喜欢
    • 2014-05-06
    • 2019-04-19
    • 2015-02-24
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多