美文网首页
LeetCode111.二叉树的最小深度

LeetCode111.二叉树的最小深度

作者: lifefruity | 来源:发表于2021-04-30 14:59 被阅读0次

    BFS来解决,主要就是层数的计算,不能重复计算,可以预先计算好当前层需要跑几次,归定好次数后就可以控制queue

        //使用BFS来做最短距离
        function minDepth($root) {
            if(!$root){
                return 0;
            }
            $step = 0;
            $queue[] = $root;
            while(count($queue)){
                $step++;
                $needRunTimes = count($queue);
                //每一层只能加一次。一层左边有,右边每有,step只能加1。比如左边有,右边没有的时候,所以array_shift的时候,不能重复加到queue中去
                for($j = 0; $j < $needRunTimes; $j++){//!!!!!这里的needRunTimes不能直接用count($queue),因为里面一直在被修改!!!!!!!!
                    $currDel = array_shift($queue);
                    if($currDel->left){
                        $queue[] = $currDel->left;
                    }
                    if($currDel->right){
                        $queue[] = $currDel->right;
                    }
    
                    if($currDel->left == null && $currDel->right == null){
                        return $step;
                    }
                }
                
            }
            return $step;
        }
    

    相关文章

      网友评论

          本文标题:LeetCode111.二叉树的最小深度

          本文链接:https://www.haomeiwen.com/subject/zubnrltx.html