diff --git a/113_path_sum_2/main.cpp b/113_path_sum_2/main.cpp new file mode 100644 index 0000000..4749865 --- /dev/null +++ b/113_path_sum_2/main.cpp @@ -0,0 +1,41 @@ +#include +using namespace std; + +struct TreeNode { + int val; + TreeNode *left; + TreeNode *right; + TreeNode() : val(0), left(nullptr), right(nullptr) {} + TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} + TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} +}; + +class Solution { + public: + vector> pathSum(TreeNode *root, int targetSum) { + vector> result; + unordered_map visited; + + function)> dfs = [&](TreeNode *root, int currentSum, vector path) { + if (!root) return; + + if (visited[root]) return; + visited[root] = true; + path.emplace_back(root->val); + currentSum += root->val; + + if (!root->left && !root->right) { + if (currentSum == targetSum) { + result.emplace_back(path); + } + } + + dfs(root->left, currentSum, path); + dfs(root->right, currentSum, path); + }; + + dfs(root, 0, {}); + + return result; + } +};