From ce8309d2cd1c5159d2a93719c6c3c3ff93ae39e2 Mon Sep 17 00:00:00 2001 From: colorbox Date: Tue, 11 Feb 2025 01:39:37 +0900 Subject: [PATCH] 112. Path Sum --- 112/step1.cpp | 21 +++++++++++++++++++++ 112/step2.cpp | 26 ++++++++++++++++++++++++++ 112/step3.cpp | 12 ++++++++++++ 3 files changed, 59 insertions(+) create mode 100644 112/step1.cpp create mode 100644 112/step2.cpp create mode 100644 112/step3.cpp 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); + } +};