-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathSolution.cpp
43 lines (41 loc) · 1.02 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
* 41 / 41 test case passed
* Status: Accepted
* Runtime: 16 ms
*/
class Solution1 {
public:
int minDepth(TreeNode* root) {
if (root == NULL) return 0;
int ans = 1;
int left = root->left ? minDepth(root->left) : 0 ;
int right= root->right ? minDepth(root->right) : 0 ;
if (left == 0) ans += right;
else if (right == 0) ans += left;
else ans += min(right, left);
return ans;
}
};
/**
* 41 / 41 test case passed
* Status: Accepted
* Runtime: 12ms
*/
class Solution2 {
public:
int minDepth(TreeNode* root) {
if (root == NULL) return 0;
int left = root->left ? minDepth(root->left) : 0 ;
int right= root->right ? minDepth(root->right) : 0 ;
return 1 + ((left == 0 || right == 0) ? max(left, right) : min(left, right));
}
};