题目链接:https://leetcode-cn.com/problems/path-sum-ii/
题目如下:
/**
* 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) {
if(!root) return res;
path.push_back(root->val);
sum+=root->val;
dfs(root,targetSum);
return res;
}
void dfs(TreeNode* root,int targetSum){
if(!root->left&&!root->right){
if(targetSum==sum){
res.push_back(path);
}
return ;
}
if(root->left){
sum+=root->left->val;
path.push_back(root->left->val);
dfs(root->left,targetSum);
path.pop_back();
sum-=root->left->val;
}
if(root->right){
sum+=root->right->val;
path.push_back(root->right->val);
dfs(root->right,targetSum);
path.pop_back();
sum-=root->right->val;
}
}
private:
vector<vector<int>> res;
vector<int> path;
int sum=0;
};