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

[leetcode] Minimum Depth of Binary Tree

时间:2014-07-03 18:54:32      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   

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.

 

思路:递归实现,取左右节点中深度小的+1。

  注意:如果左右子树其中一个为null,则应以不为null的子树深度为准,而不是以null的深度0为准。

 

bubuko.com,布布扣
public class Solution {

    public int minDepth(TreeNode root) {
        if (root == null)
            return 0;
        if (root.left == null)
            return minDepth(root.right) + 1;
        if (root.right == null)
            return minDepth(root.left) + 1;
        else

        {
            int minLeft = minDepth(root.left);
            int minRight = minDepth(root.right);
            return (minLeft < minRight ? minLeft : minRight) + 1;
        }
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(5);
        root.right = new TreeNode(5);
        root.right.left = new TreeNode(9);

        System.out.println(new Solution().minDepth(root));
    }
}
View Code

 

[leetcode] Minimum Depth of Binary Tree,布布扣,bubuko.com

[leetcode] Minimum Depth of Binary Tree

标签:des   style   blog   http   color   os   

原文地址:http://www.cnblogs.com/jdflyfly/p/3821430.html

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