Skip to content

Commit aeac2ee

Browse files
authored
Merge pull request #36 from colorbox/111
111. Minimum Depth of Binary Tree
2 parents 37a31dc + ba2d5f3 commit aeac2ee

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

111/step1.cpp

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/*
2+
Solve Time : 07:17
3+
4+
Time : O(V + E)
5+
Space : O(V)
6+
7+
root ~ leafまでの距離、という部分を読み違えて時間を多少ロスしたものの、特につまるところなく解けた。
8+
*/
9+
class Solution {
10+
public:
11+
int minDepth(TreeNode* root) {
12+
queue<pair<TreeNode*, int>> nodes_and_depths;
13+
nodes_and_depths.emplace(root, 1);
14+
while (!nodes_and_depths.empty()) {
15+
auto [node, depth] = nodes_and_depths.front();
16+
nodes_and_depths.pop();
17+
if (!node) {
18+
continue;
19+
}
20+
if (node->left == nullptr && node->right == nullptr) {
21+
return depth;
22+
}
23+
nodes_and_depths.emplace(node->left, depth + 1);
24+
nodes_and_depths.emplace(node->right, depth + 1);
25+
}
26+
return 0;
27+
}
28+
};

111/step2.cpp

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/*
2+
Time : O(V + E)
3+
Space : O(V)
4+
5+
再帰,DFSで解いてみる。
6+
rootの処理をどうしても分岐で処理できなかったので最初のrootの面倒を見る関数と再帰処理をする関数とに分けた。
7+
*/
8+
class Solution {
9+
public:
10+
int minDepth(TreeNode* root) {
11+
if (!root) {
12+
return 0;
13+
}
14+
return minDepthRecursive(root);
15+
}
16+
private:
17+
int minDepthRecursive(TreeNode* root) {
18+
if (!root) {
19+
return numeric_limits<int>::max();
20+
}
21+
if (root->left == nullptr && root->right == nullptr) {
22+
return 1;
23+
}
24+
return min(minDepthRecursive(root->left), minDepthRecursive(root->right)) + 1;
25+
}
26+
};

111/step3.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
public:
3+
int minDepth(TreeNode* root) {
4+
queue<pair<TreeNode*, int>> nodes_and_depths;
5+
nodes_and_depths.emplace(root, 1);
6+
while (!nodes_and_depths.empty()) {
7+
auto [node, depth] = nodes_and_depths.front();
8+
nodes_and_depths.pop();
9+
if (!node) {
10+
continue;
11+
}
12+
if (!(node->left || node->right)) {
13+
return depth;
14+
}
15+
nodes_and_depths.emplace(node->left, depth + 1);
16+
nodes_and_depths.emplace(node->right, depth + 1);
17+
}
18+
return 0;
19+
}
20+
};

0 commit comments

Comments
 (0)