/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @param targetSum int整型 * @return bool布尔型 */ bool dfs(TreeNode* root, int targetSum) { if(!root) { return false; } targetSum -= root->val; // 到达子节点 if(!root->left && !root->right) { // cout << root->val << ", " << targetSum-root->val << endl; if(targetSum == 0) return true; else return false; } return dfs(root->left, targetSum) || dfs(root->right, targetSum); } bool hasPathSumII(TreeNode* root, int targetSum) { // write code here // 注意题目要求是任意节点到其子节点,则起始节点可以不是根节点; if(!root) { return false; } if(dfs(root, targetSum)) return true; return hasPathSumII(root->left, targetSum) || hasPathSumII(root->right, targetSum); } };