leetcode-树练习-minimum-depth-of-binary-tree

minimum-depth-of-binary-tree

https://www.nowcoder.com/practice/e08819cfdeb34985a8de9c4e6562e724?tpId=46&tqId=29030&tPage=1&rp=1&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking

求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。
Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

真是一道奇怪的题目:为什么我写的递归的方案一直不可以。不行的原因我们后续再探讨,先把这道题目结束了。

public class Solution {

     int minDepth = Integer.MAX_VALUE;
     void help(TreeNode root, int depth){
        if(root.left == null && root.right == null){
            if(depth < minDepth)
                minDepth = depth;
        }else{
            if(root.left != null)
                help(root.left, depth+1);
            if(root.right != null)
                help(root.right, depth+1);
        }
    }
    public int run(TreeNode root) {

        if(root == null)return 0;
        else{
            help(root, 1);
            return minDepth;
        }


    }
}

先参考下面的这个思路完成这道题目,应该是可以的,这种思路也是我在追求实现的,因为理解起来比较直观。

来个非递归的,思路是层序遍历,找到第一个左右结点都为null的情况,就返回
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
    pu

剩余60%内容,订阅专栏后可继续查看/也可单篇购买

小白刷Leetcode 文章被收录于专栏

那些必刷的leetcode

全部评论
一模一样,为啥运行的和本地结果不一样呢
点赞 回复 分享
发布于 2020-04-15 10:22

相关推荐

谁知道呢_:你好,我是炮灰n+1号
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务