// @lc code=start /** * Definition for a binary tree node. * 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) {} * }; */ classSolution { public: boolhasPathSum(TreeNode* root, int targetSum){ if (root == nullptr) returnfalse; return traversal(root, targetSum - root->val); } private: booltraversal(TreeNode* root, int sum){ if (!root->left && !root->right && sum==0) returntrue; if (!root->left && !root->right) returnfalse;
if (root->left) { if (traversal(root->left, sum - root->left->val)) returntrue; } if (root->right) { if (traversal(root->right, sum - root->right->val)) returntrue; } returnfalse; } }; // @lc code=end