Conversation
| #### 感想 | ||
| - stackの変数名はnodes_and_totalsがいいか | ||
| - "||"のような記号の後に改行するよりか、その前で改行した方が見やすいのか https://peps.python.org/pep-0008/#should-a-line-break-before-or-after-a-binary-operator | ||
| - 下が揃っていた方が見やすいという人もいるのかな |
There was a problem hiding this comment.
Google C++ は、末尾に && があるのがより普通でした。
https://google.github.io/styleguide/cppguide.html#Boolean_Expressions
わりとこれは場所によりますね。
There was a problem hiding this comment.
ありがとうございます。
とりあえず末尾に置くようにしてコードを書いてみて、それが見にくいシーンに出会ったらまた考えたいと思います。
| return HasPathSumHelper(root, targetSum, 0); | ||
| } | ||
| private: | ||
| bool HasPathSumHelper(TreeNode* node, int targetSum, int total) { |
There was a problem hiding this comment.
この問題だとHelperを使わない再帰の書き方もありますね。そのほうがコンパクトになり、またtotalに関する議論もなくなるので個人的には好きですが、他の問題ではHelperを使ったほうが見通し良いものもあるので、単なる好みの範疇かもしれません。
There was a problem hiding this comment.
ありがとうございます。
他の方のコードがちゃんと読めていませんでした。
以下のように、targetSumを減らしながら判定することで、Helperが不要で、かつtotalも不要で書けることを確認しました。
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) {
return false;
}
if (IsLeaf(root) && targetSum == root->val) {
return true;
}
return hasPathSum(root->left, targetSum - root->val) ||
hasPathSum(root->right, targetSum - root->val);
}
private:
bool IsLeaf(TreeNode* node) {
return !node->left && !node->right;
}
};There was a problem hiding this comment.
targetSumと一致するかのところですが、
葉ノードでこれより下のノードにいくことはないので、
以下のようにしても良いですね。
if (IsLeaf(root)) {
return root->val == targetSum;
}| } | ||
| return false; | ||
| } | ||
| private: |
There was a problem hiding this comment.
趣味ですが、この程度の関数なら関数化せずにコメントで説明するほうが好きです。
| return false; | ||
| } | ||
| // pair = (node, total_value) | ||
| std::queue<std::pair<TreeNode*, int>> node_to_visit; |
There was a problem hiding this comment.
step3 のように nodes_*** 複数形にすると、複数の値が含まれることが読み手に取って分かりやすくなると思いました。
This Problem
Path Sum
Next Problem
Binary Tree Level Order Traversal