LeetCode 111. Minimum Depth of Binary Tree

原题链接在这里:https://leetcode.com/problems/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.

题解:

Maximum Depth of Binary Tree相似。

不同是多了判断叶子节点,若是给出[1,2]这种情况,返回值应该是2而不是1, 即使root的右节点为空,但根据定义:The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. 此时root.left不为null, 所以root不能被认为是leaf. 因此加了if(root.left == null) return right+1, 这里注意加一。

Time Complexity: O(n)最坏的情况每个节点走了一遍. Space: O(logn), recursion stack 是 tree 的高度是logn.

AC Java:

 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     public int minDepth(TreeNode root) {
12         if(root == null){
13             return 0;
14         }
15         
16         int left = minDepth(root.left);
17         int right = minDepth(root.right);
18         
19         if(root.left == null){
20             return right+1;    
21         }
22         if(root.right == null){
23             return left+1;
24         }
25         
26         return Math.min(left, right)+1;
27     }
28 }

AC C++: 

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     int minDepth(TreeNode* root) {
15         if(!root){
16             return 0;
17         }
18 
19         int l = minDepth(root->left);
20         int r = minDepth(root->right);
21         if(!root->left){
22             return r + 1;
23         }
24 
25         if(!root->right){
26             return l + 1;
27         }
28 
29         return min(l, r) + 1;
30     }
31 };

 

posted @ 2015-09-05 01:07  Dylan_Java_NYC  阅读(254)  评论(0编辑  收藏  举报