思路:
dfs
代码:
/**
* 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) {
if(root) return dfs(root,targetSum);
return false;
}
bool dfs(TreeNode* root,int targetSum){
int tmp=root->val;
targetSum-=root->val;
if(!root->left && !root->right && !targetSum) return true;
else{
if(root->left){
if(dfs(root->left,targetSum)) return true;
}
if(root->right){
if(dfs(root->right,targetSum)) return true;
}
}
targetSum+=tmp;
return false;
}
};
评论区