用循环和栈代替递归Demo

用循环和栈代替递归Demo

用循环和栈代替递归Demo_第1张图片

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则递归
        }
 }

用循环和栈代替递归:

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();
            }
        }
    }
 }

 
  


你可能感兴趣的:(算法)