码迷,mamicode.com
首页 > 其他好文 > 详细

111. 二叉树的最小深度

时间:2019-06-28 09:15:56      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:dep   static   一个   ==   ret   code   val   imu   class   

给定一个二叉树,找出其最小深度。

最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

说明: 叶子节点是指没有子节点的节点。

示例:

给定二叉树 [3,9,20,null,null,15,7],

3
/ \
9 20
/ \
15 7
返回它的最小深度  2.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree

public class MinimumDepthofBinaryTree {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode (int x) {
            val = x;
        }
    }
    
    public int minDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }
        int leftDepth = minDepth(root.left);
        int rightDepth = minDepth(root.right);
        //修改返回条件,如果某节点只有一个孩子,此时非叶子节点,所以返回的应该是有孩子的那一部分,且加1(包括该节点)
        if (leftDepth == 0 || rightDepth == 0) {
            return leftDepth + rightDepth + 1;
        }
        return Math.min(leftDepth, rightDepth) + 1;
    }
}

 

111. 二叉树的最小深度

标签:dep   static   一个   ==   ret   code   val   imu   class   

原文地址:https://www.cnblogs.com/xiyangchen/p/11100544.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!