递归
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 * @param sum int整型 * @return bool布尔型 */ bool hasPathSum(TreeNode* root, int sum) { // write code here target = sum; helper(root, 0); return isExist; } bool isExist = false; int target; void helper(TreeNode* root, int sum){ if(root == NULL) return; //if(sum > target) return; 节点值未必是正数! sum += root -> val; if(root -> left == NULL && root -> right == NULL){ if(sum == target) isExist = true; }else{ if(!isExist) helper(root -> left, sum); if(!isExist) helper(root -> right, sum); } } };