二叉树的最小深度 【leetcode - 111 - 简单】

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Tomwildboar/article/details/86232372

文章优先发表在个人博客  http://www.xdx97.com/#/single?bid=4c7196c2-e935-c582-f38c-ff8ab8f0e28a

    胡扯:自从 明白了 用递归遍历二叉树,感觉这样的题已经没有什么难度了。 但是很奇怪为什么这个题的通过率只有 35.5%,去看了一下评论,大概明白了,很多人是没有看明白题目的要求。是   根节点到叶子节点

思路:

    1、日常非空判断。

    2、看明白题目,是求到 叶子节点的 最小深度。

    3、下面给出代码,为了跟好的理解,多加了一个输出。如果要提交请注释掉。

代码

class Solution {
    //初始化 -1 表示无穷大
    int min = -1;    //最小深度
    // current 当前深度
    void dfs (TreeNode root,int current){
        if ( root.left == null && root.right == null ){
            System.out.println(root.val + " : "+current);            
            if ( min == -1 || current < min )
                min = current;
            return;
        }
        if (root.left != null)
            dfs(root.left,current+1);
        if (root.right != null)
            dfs(root.right,current+1);
    }
    public int minDepth(TreeNode root) {
        if (root == null)
            return 0;
        dfs(root,1);
        return min;
    }
}

猜你喜欢

转载自blog.csdn.net/Tomwildboar/article/details/86232372
今日推荐