/**
* 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:boolpreOrderPathSum(TreeNode* p,int count){if(!p -> left &&!p -> right && count ==0)returntrue;if(!p -> left &&!p -> right)returnfalse;if(p -> left){
count -= p -> left -> val;if(preOrderPathSum(p -> left, count))returntrue;
count += p -> left -> val;}if(p -> right){
count -= p -> right -> val;if(preOrderPathSum(p -> right, count))returntrue;
count += p -> right -> val;}returnfalse;}boolhasPathSum(TreeNode* root,int targetSum){if(root ==nullptr)returnfalse;returnpreOrderPathSum(root, targetSum - root -> val);}};
精简后
classSolution{public:boolhasPathSum(TreeNode* root,int sum){if(!root)returnfalse;if(!root->left &&!root->right && sum == root->val){returntrue;}returnhasPathSum(root->left, sum - root->val)||hasPathSum(root->right, sum - root->val);}};