用循环和栈代替递归Demo
Q:将上图的数据结构转换为如下要求:
循环中嵌套递归:
public function recursion($arr, $str)
{
for($i = 0; $i < count($arr); $i++){
$newstr = $str + '->'+ $arr[$i]['resource_name'];//字符串连接
if(! array_key_exists('children', $arr[$i])
PrintOUT $newstr;
else
$this->recursion($arr[$i]['children'], $newstr);//存在chilrden则递归
}
}用循环和栈代替递归:
<pre name="code" class="php">public function recursion($arr)
{
stack ;
$i = 0;
$str = "";
while(1){
$newstr = $str + '->'+ $arr[$i]['resource_name'];//字符串连接
if(array_key_exists('children', $arr[$i])
if($i+1 < count($arr)){
$param.push($arr, $str, $i+1);
}
$arr = $arr[$i]['children'];
$i = 0;
$str = $newstr;
}else {
PrintOUT $newstr;
if($i+1 < count($arr)){
$i = $i + 1;
}else{
if($param.isempty()) break;
$arr, $str, $i = $param.pop();
}
}
}
}
该博客展示了如何使用循环和栈来替代递归解决数据结构转换问题,具体包括一个循环中嵌套递归的实例。
1139

被折叠的 条评论
为什么被折叠?



