首页 > 其他 > 详细

[leetcode] Minimum Depth of Binary Tree

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!