35 lines
986 B
C++
35 lines
986 B
C++
/**
|
|
* 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>> result;
|
|
vector<int> path;
|
|
void dfs(TreeNode* root, vector<int>& path, int sum, int target){
|
|
if(root == nullptr) return;
|
|
|
|
path.push_back(root->val);
|
|
sum += root->val;
|
|
|
|
if(sum == target && root->left == nullptr && root->right == nullptr){
|
|
result.push_back(path);
|
|
}
|
|
|
|
dfs(root->left, path, sum, target);
|
|
dfs(root->right, path, sum, target);
|
|
|
|
path.pop_back();
|
|
}
|
|
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
|
|
dfs(root, path, 0, targetSum);
|
|
return result;
|
|
}
|
|
}; |