1、其实就是树的前序遍历,也可以说是深度优先搜索。
注意,这种做法在可能返回false时需要减去当前结点的值,但是如果是返回true则不用,因为如果存在一个分支返回true,最后结果必然是true,后面的判断结果已经不重要了。
/**
* 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) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
int sum=0;
bool result=dfs(sum,root,targetSum);
return result;
}
bool dfs(int& sum,TreeNode* root,int targetSum)
{
if(root==NULL) return false;
sum+=root->val;
if(sum==targetSum&&root->right==NULL&&root->left==NULL) return true;
bool one=dfs(sum,root->left,targetSum);
bool two=dfs(sum,root->right,targetSum);
sum-=root->val;
return one||two;
}
};