码迷,mamicode.com
首页 > 编程语言 > 详细

155. Minimum Depth of Binary Tree【LintCode by java】

时间:2018-05-29 11:56:35      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:span   ret   nod   its   app   pat   code   偏差   lintcode   

Description

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.

Example

Given a binary tree as follow:

  1
 / \ 
2   3
   /   4   5  

The minimum depth is 2.

题意:求二叉树的最小深度。至于这个最小深度该怎么理解呢?接触的比较多的是最大深度,即根结点到离它最远的叶子结点的距离(包括首尾),这里的距离当然是指结点的个数。显然,最小深度就是根结点到离它最近的结点之间距离。虽然知道是这个意思,在一开始的理解上还有点偏差。例如,我想如果根结点只有右子树,那么这个最小深度怎么算,是不是就是1了,因为左子树为空嘛。后来仔细想想,其实不然,左子树为空的话,如果右子树不为空,说明根结点(其他结点亦然)不是叶子点,还得继续求右子树的深度(对应于代码的第26和29行),直到遇到叶子结点。代码如下:

 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 public class Solution {
14     /**
15      * @param root: The root of binary tree
16      * @return: An integer
17      */
18     public int minDepth(TreeNode root) {
19         // write your code here
20         if(root==null){
21             return 0;
22         }
23         if(root.left==null&&root.right==null){
24             return 1;
25         }
26         if(root.left==null){
27             return minDepth(root.right)+1;
28         }
29         if(root.right==null){
30             return minDepth(root.left)+1;
31         }
32         return Math.min(minDepth(root.left),minDepth(root.right))+1;
33     }
34 }

 

 

155. Minimum Depth of Binary Tree【LintCode by java】

标签:span   ret   nod   its   app   pat   code   偏差   lintcode   

原文地址:https://www.cnblogs.com/phdeblog/p/9104130.html

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