我有一个 $branch 对象,它可以包含其他 $branch 对象:
$branch->children();
他们每个人小时候都可以拥有$苹果。
$branch->apples();
如何从 $branch 递归收集所有 $apples?
function collectApples($branch){
$apples = array();
?
return $apples;
}
使用以下方法收集特定分支的所有苹果DFS https://en.wikipedia.org/wiki/Depth-first_search:
function collectApples($branch) {
$apples = $branch->apples();
foreach ($branch->children() as $child) {
$apples = array_merge($apples, collectApples($child));
}
return $apples;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)