From b883e27508063ee760d6f75de997853895a112bd Mon Sep 17 00:00:00 2001 From: SquidSpirit Date: Wed, 12 Mar 2025 23:50:42 +0800 Subject: [PATCH] feat: 112_path_sum --- 112_path_sum/main.cpp | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 112_path_sum/main.cpp diff --git a/112_path_sum/main.cpp b/112_path_sum/main.cpp new file mode 100644 index 0000000..2d56916 --- /dev/null +++ b/112_path_sum/main.cpp @@ -0,0 +1,34 @@ +#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: + bool hasPathSum(TreeNode *root, int targetSum) { + unordered_map visited; + + function dfs = [&](TreeNode *root, int currentSum) -> bool { + if (!root) return false; + + if (visited[root]) return false; + visited[root] = true; + currentSum += root->val; + + if (!root->left && !root->right) { + return currentSum == targetSum; + } + + return dfs(root->left, currentSum) || dfs(root->right, currentSum); + }; + + return dfs(root, 0); + } +};