-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path111_Minimum Depth of Binary Tree.cpp
68 lines (58 loc) · 1.71 KB
/
111_Minimum Depth of Binary Tree.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* 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 == NULL )
return 0;
if ( root->right == NULL )
return minDepth(root->left)+1;
else if ( root->left == NULL )
return minDepth(root->right)+1;
else
return min(minDepth(root->left), minDepth(root->right))+1;
}
};
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* 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;
else if ( !root->left && !root->right )
return 1;
vector<TreeNode*> tmp;
tmp.push_back(root);
int count = 0;
while ( !tmp.empty() ) {
count++;
int n = tmp.size();
for ( int i = 0; i < n; i++ ) {
TreeNode* node = tmp.back();
tmp.pop_back();
if ( node->left == NULL && node->right == NULL )
return count;
if ( node->left )
tmp.insert(tmp.begin(), node->left);
if ( node->right )
tmp.insert(tmp.begin(), node->right);
}
}
}
};