-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC111MinDepth
28 lines (26 loc) · 878 Bytes
/
LC111MinDepth
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
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == nullptr) return 0;
queue<TreeNode*> nodes;
nodes.push(root);
int minDepth = 1, levelSize = 1, seenOnCurrentLevel = 0;
while (!nodes.empty()){
if (nodes.front()->left == nullptr && nodes.front()->right == nullptr){
return minDepth;
}
seenOnCurrentLevel++;
if (nodes.front()->left != nullptr)
nodes.push(nodes.front()->left);
if (nodes.front()->right != nullptr)
nodes.push(nodes.front()->right);
nodes.pop();
if (levelSize == seenOnCurrentLevel){
levelSize = nodes.size();
seenOnCurrentLevel = 0;
minDepth++;
}
}
return -1;
}
};