【发布时间】: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 以表示在该分支中没有找到任何东西(并且找不到任何东西),因此“父”调用将知道继续到下一个兄弟节点。