class Solution {
public:
// bool hasPathSum(TreeNode* root, int targetSum) {
// if (root == nullptr)
// return false;
//这里和0相等是不对的,因为它到下一层才减去
// if (root->right == nullptr && root->left == nullptr && targetSum == 0)
// return true;
// return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);
// }
bool hasPathSum(TreeNode* root, int sum) {
if (root == nullptr) return false;
if (!root->left && !root->right && sum == root->val) {
return true;
}
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
};
/**
* 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:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<vector<int>> ans;
vector<int> helper;
if (root == nullptr)
return ans;
backtrace(ans, helper, root, targetSum);
return ans;
}
void backtrace(vector<vector<int>>& ans, vector<int>& helper, TreeNode* root, int targetSum){
helper.push_back(root->val);
if (root->left == nullptr && root->right == nullptr && targetSum == root->val)
{
ans.push_back(helper);
return;
}
if (root->left == nullptr && root->right == nullptr)
return;
if (root->left){
backtrace(ans, helper, root->left, targetSum - root->val);
helper.pop_back();
}
if (root->right){
//helper.push_back(root->val);
backtrace(ans, helper, root->right, targetSum - root->val);
helper.pop_back();
}
return ;
}
};