0%

111. Minimum Depth of Binary Tree

104. Maximum Depth of Binary Tree对比
这道题要特别注意一个corner case
[1,2]的mindepth是2不是1
所以不能简单的一行递归

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