/**
* 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:
void traversal(TreeNode* cur, int count)
{
if(cur->left == nullptr && cur->right == nullptr && count == 0)
{
res.push_back(path);
path.clear();
return ;
}
if(cur->left == nullptr && cur->right == nullptr)
{
return ;
}
if(cur->left)
{
path.push_back(cur->left->val);
count -= cur->left->val;
traversal(cur->left, count);
count += cur->left->val;
path.pop_back();
}
if(cur->right)
{
path.push_back(cur->right->val);
count -= cur->right->val;
traversal(cur->right, count);
count += cur->right->val;
path.pop_back();
}
return ;
}
vector<vector<int>> pathSum(TreeNode* root, int targetSum)
{
if(root == nullptr)
{
return res;
}
res.clear();
path.clear();
path.push_back(root->val);
traversal(root, targetSum - root->val);
return res;
}
private:
vector<vector<int>> res;
vector<int> path;
};