Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions 111/step1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/*
Solve Time : 07:17

Time : O(V + E)
Space : O(V)

root ~ leafまでの距離、という部分を読み違えて時間を多少ロスしたものの、特につまるところなく解けた。
*/
class Solution {
public:
int minDepth(TreeNode* root) {
queue<pair<TreeNode*, int>> nodes_and_depths;
nodes_and_depths.emplace(root, 1);
while (!nodes_and_depths.empty()) {
auto [node, depth] = nodes_and_depths.front();
nodes_and_depths.pop();
if (!node) {
continue;
}
if (node->left == nullptr && node->right == nullptr) {
return depth;
}
nodes_and_depths.emplace(node->left, depth + 1);
nodes_and_depths.emplace(node->right, depth + 1);
}
return 0;
}
};
26 changes: 26 additions & 0 deletions 111/step2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
Time : O(V + E)
Space : O(V)

再帰,DFSで解いてみる。
rootの処理をどうしても分岐で処理できなかったので最初のrootの面倒を見る関数と再帰処理をする関数とに分けた。
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) {
return 0;
}
return minDepthRecursive(root);
}
private:
int minDepthRecursive(TreeNode* root) {
if (!root) {
return numeric_limits<int>::max();
}
if (root->left == nullptr && root->right == nullptr) {
return 1;
}
return min(minDepthRecursive(root->left), minDepthRecursive(root->right)) + 1;
}
};
20 changes: 20 additions & 0 deletions 111/step3.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution {
public:
int minDepth(TreeNode* root) {
queue<pair<TreeNode*, int>> nodes_and_depths;
nodes_and_depths.emplace(root, 1);
while (!nodes_and_depths.empty()) {
auto [node, depth] = nodes_and_depths.front();
nodes_and_depths.pop();
if (!node) {
continue;
}
if (!(node->left || node->right)) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

私は、

!node->left && !node->right

のほうが好きですが、趣味の範囲でしょうか。

この問題がこれくらいで書けていたら特に問題ないと思います。

return depth;
}
nodes_and_depths.emplace(node->left, depth + 1);
nodes_and_depths.emplace(node->right, depth + 1);
}
return 0;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ここがでてくるのは、root == nullptr のときだけでしょうか。一番上にするのも一つかなと思います。

}
};