要求:从根开始
思路:坑点:和可以负数
/**
* 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>> v;
vector<int> tmp;
void dfs(TreeNode* root,int target,int sum){
if(!root)return;
tmp.push_back(root->val);
if(sum==target&&!root->left&&!root->right){
v.push_back(tmp);
tmp.pop_back();
return;
}
if(root->left)dfs(root->left,target,sum+root->left->val);
if(root->right)dfs(root->right,target,sum+root->right->val);
tmp.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int target) {
if(!root)return {};
dfs(root,target,root->val);
return v;
}
};