LeetCode 111. Minimum Depth of Binary Tree (二叉树最小的深度)

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.

 


 

题目标题:Tree

  这道题目给了我们一个二叉树,让我们找到它最小的深度,注意这里的最小深度是指root 到一个 leaf node。

  举个例子:  1

                             /

         2

      /

     3

  这种情况,最小depth 是3, 而不是因为1的right 是null ,最小depth 就等于1了。

  和求最大深度差不多,每次遇到null node 返回0。接着每一个点返回 left 和right 中小的那一个depth + 1。但是我们需要控制住一个情况,就是如果parent 的left 和right 其中有一个返回的是0, 意思是有一个null 点, 那么这里就不能取两个child 中小的那个了,因为一个点是null, 另一个不是,那么就说明,null点不是leaf 点。 这种情况只需要返回那个不是null 的点的 depth + 1 就可以了。

 

Java Solution:

Runtime beats 17.13% 

完成日期:07/03/2017

关键词:Tree

关键点:设条件控制住left 和right 其中一个点是null 的这种情况,另外返回其他值

 

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution 
11 {
12     public int minDepth(TreeNode root) 
13     {
14         if(root == null)
15             return 0;
16         
17         int left_depth = minDepth(root.left);
18         int right_depth = minDepth(root.right);
19         
20         if(left_depth == 0 && right_depth != 0)
21             return right_depth + 1;
22         else if(left_depth != 0 && right_depth == 0)
23             return left_depth + 1;
24         else
25             return Math.min(left_depth, right_depth) + 1;
26     }
27 }

参考资料:N/A

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

posted @ 2017-07-04 05:28  Jimmy_Cheng  阅读(282)  评论(0编辑  收藏  举报