Skip to content
Open
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
21 changes: 21 additions & 0 deletions 112/step1.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
Solve Time : 03:57

Time : O(N)
Space : O(N)

再帰でざっくりと実装、特に悩むことなく実装完了
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int target_sum) {
if (!root) {
return false;
}
if (!root->left && !root->right) {
return target_sum == root->val;
}
return hasPathSum(root->left, target_sum - root->val) || hasPathSum(root->right, target_sum - root->val);
}
};

26 changes: 26 additions & 0 deletions 112/step2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*
Time : O(N)
Space : O(N)

再帰ではなく、stackを使って実装
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int target_sum) {
stack<pair<TreeNode*, int>> nodes_and_sums;
nodes_and_sums.emplace(root, target_sum);
while (!nodes_and_sums.empty()) {
auto [node, sum] = nodes_and_sums.top();
nodes_and_sums.pop();
if (!node) {
continue;
}
Copy link

Choose a reason for hiding this comment

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

sum -= node->val
先にしたほうが素直ではないですかね。どちらでもいいですが。あと、名前的には、sum というよりは残りですかね。
https://docs.google.com/document/d/11HV35ADPo9QxJOpJQ24FcZvtvioli770WWdZZDaLOfg/edit?tab=t.0#heading=h.ed3x3pkyeqkp

Copy link
Owner Author

Choose a reason for hiding this comment

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

減算しているので残りという概念のほうが適切ですね、ありがとうございます。

if (!node->left && !node->right && sum == node->val) {
Copy link

Choose a reason for hiding this comment

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

sum == target_sumとなるかと思ったら違ったので少し戸惑いました。sumという変数名を使うなら足し上げていくか、odaさんも指摘されているようにcomplementやrest_sumのような「残り」を意味する変数名を使うという選択肢があると思います

Copy link
Owner Author

Choose a reason for hiding this comment

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

コメントありがとうございます。
たしかに、sumと言う名前であれば足し上げていくほうが素直ですね。

return true;
}
nodes_and_sums.emplace(node->left, sum - node->val);
nodes_and_sums.emplace(node->right, sum - node->val);
}
return false;
}
};
12 changes: 12 additions & 0 deletions 112/step3.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
class Solution {
public:
bool hasPathSum(TreeNode* root, int target_sum) {
if (!root) {
return false;
}
if (!root->left && !root->right) {
return target_sum == root->val;
}
return hasPathSum(root->left, target_sum - root->val) || hasPathSum(root->right, target_sum - root->val);
}
};