diff --git a/112/step1.cpp b/112/step1.cpp new file mode 100644 index 0000000..0c292be --- /dev/null +++ b/112/step1.cpp @@ -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); + } +}; + diff --git a/112/step2.cpp b/112/step2.cpp new file mode 100644 index 0000000..7c0c461 --- /dev/null +++ b/112/step2.cpp @@ -0,0 +1,26 @@ +/* +Time : O(N) +Space : O(N) + +再帰ではなく、stackを使って実装 +*/ +class Solution { +public: + bool hasPathSum(TreeNode* root, int target_sum) { + stack> 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; + } + if (!node->left && !node->right && sum == node->val) { + return true; + } + nodes_and_sums.emplace(node->left, sum - node->val); + nodes_and_sums.emplace(node->right, sum - node->val); + } + return false; + } +}; diff --git a/112/step3.cpp b/112/step3.cpp new file mode 100644 index 0000000..26cba5d --- /dev/null +++ b/112/step3.cpp @@ -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); + } +};