-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path111.cpp
42 lines (41 loc) · 921 Bytes
/
111.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
// conciseIdea.cpp
class Solution {
public:
int minDepth(TreeNode *root) {
if (!root)
return 0;
if (!root->left)
return 1 + minDepth(root->right);
if (!root->right)
return 1 + minDepth(root->left);
return 1 + min(minDepth(root->left), minDepth(root->right));
}
};
// recursion.cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution2 {
int min = INT_MAX;
public:
int minDepth(TreeNode *root) {
if (!root)
return 0;
searchDepth(root, 1);
return min;
}
void searchDepth(TreeNode *root, int depth) {
if (root == NULL)
return;
if (!root->left && !root->right)
min = min < depth ? min : depth;
searchDepth(root->left, depth + 1);
searchDepth(root->right, depth + 1);
}
};