Conversation
| if (node->left) { | ||
| next_nodes.push_back(node->left); | ||
| } | ||
| if (node->right) { | ||
| next_nodes.push_back(node->right); | ||
| } |
There was a problem hiding this comment.
とりあえず push_back して、出てきたものが nullptr でないかを確認するというのもありでしょう。
今回、特に問題ないかと思います。
There was a problem hiding this comment.
ありがとうございます。
以下のようにできることを確認しました。配列に無効なノードは入りますが、例外処理をまとめて行えるので今回はこちらが良いと思いました。どうしても自分は配列に入るものが有効である保証があることを考えるのですが、今回のように、そうでなくても良いか、それで楽になる部分はないか考えてみようと思います。
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) {
return 0;
}
std::vector<TreeNode*> current_nodes;
current_nodes.push_back(root);
int depth = 1;
while (true) {
std::vector<TreeNode*> next_nodes;
for (auto node : current_nodes) {
if (!node) {
continue;
}
if (!node->left && !node->right) {
return depth;
}
next_nodes.push_back(node->left);
next_nodes.push_back(node->right);
}
depth++;
std::swap(current_nodes, next_nodes);
}
}
};| } | ||
| } | ||
| depth++; | ||
| std::swap(current_nodes, next_nodes); |
There was a problem hiding this comment.
current_nodes.swap(next_nodes); というのもあります。
There was a problem hiding this comment.
ありがとうございます。こちらはstd::vectorのメンバ関数と理解いています。
current "を" next "と" 入れ替えるニュアンス出せると思いました
| } | ||
| std::vector<TreeNode*> current_nodes; | ||
| current_nodes.push_back(root); | ||
| int depth = 1; |
There was a problem hiding this comment.
depthは0始まりであってほしいという指摘を受けたことかあります。
0始まりだと更新タイミングがわかりにくくなってしまうので、趣味だと思います。
olsen-blue/Arai60#27 (comment)
There was a problem hiding this comment.
ありがとうございます。
自分の感覚では、swapの操作とdepthのインクリメントを1ループの締めの処理としてまとめた方が見やすいと感じているので、こうしてみました。
| } | ||
| return -1; //input_error | ||
| } | ||
| }; |
There was a problem hiding this comment.
良いと思います。
だいぶ細かいところで恐縮ですが、36行目はleftからrightにしたくなりました。
処理が複雑になっていった時に、操作の順序が意図的なのか混乱する気がするというのが理由です。
There was a problem hiding this comment.
ありがとうございます。
こちらはおっしゃる通りですね、特に意味がない限り、統一してleft,rightにします。
This Problem
Minimum Depth of Binary Tree
Next Problem
Merge Two Binary Trees