【问题标题】:Find element by id in tree data structure在树数据结构中按 id 查找元素
【发布时间】:2016-10-05 04:20:00
【问题描述】:

树样例:

           root
           / | \
          1  2  4
         /      /|\
        3      5 6 7
       / \
      13 14

我有一个功能,即递归搜索树中的元素。例如我想找到元素#6

public function getChildById($root,$id){

        if (!empty($root->nodes)){
            foreach ($root->nodes as $node){

                echo $node->getId()."<br>";

                if ($node->getId()==$id){
                    //if i wrote here 'echo $node->getId(), it successful find current way and last id, but the result of that return is nothing'
                    return $node;
                }else{
                    //if i add here return , it newer find 6 elemement, it stops on 13
                    /*return*/ $this->getChildById($node, $id);  
                }

            }
        }
    }

我写了一些cmets,请帮帮我,我做错了什么?

【问题讨论】:

  • 您没有捕获递归调用的返回值。并且无法发出搜索失败的信号(例如,当您到达节点 13 时,您必须返回 SOMETHING 以表示在该分支中没有找到任何东西(并且找不到任何东西),因此“父”调用将知道继续到下一个兄弟节点。

标签: php tree php-5.3


【解决方案1】:

真相确实在中间:当你不返回递归调用的值时,你会丢失你收集的信息。另一方面,当您返回递归调用的值时,它将不起作用,因为您将在foreach 循环的第一次迭代中始终返回。

因此,您有时需要返回它:仅当您在递归部分有匹配时。如果没有成功,则不应返回并继续 foreach 循环:

public function getChildById($root, $id){
    if (!empty($root->nodes)){
        foreach ($root->nodes as $node){
            if ($node->getId()==$id){
                return $node;
            } else {
                $found = $this->getChildById($node, $id);
                if ($found) return $found;
            }           
        }
    }
}   

查看它在eval.in 上运行。

请注意,在根上进行匹配测试更为常见,因此在函数的开头。归根结底是一样的,除了如果值在你调用函数的根目录上,它也会被找到!

public function getChildById($root, $id){
    if ($root->getId()==$id) return $root;
    foreach ($root->nodes as $node){
        $found = $this->getChildById($node, $id);
        if ($found) return $found;
    }           
}   

【讨论】:

  • 非常感谢!现在我明白了
猜你喜欢
  • 2014-12-25
  • 2020-11-25
  • 2019-03-30
  • 2013-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-06
  • 1970-01-01
相关资源
最近更新 更多