Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example:
Given the below binary tree and
Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> res;
vector<int> ans;
vector<vector<int>> pathSum(TreeNode* root, int sum) {
res.clear();
ans.clear();
if(root==NULL)
return res;
pathSum1(root, sum);
return res;
}
void pathSum1(TreeNode* root, int sum)
{
ans.push_back(root->val);
if (root!=NULL&&root->left == NULL && root->right == NULL && root->val == sum)
{
res.push_back(ans);
return;
}
if(root!=NULL&&root->left!= NULL )
{
pathSum1(root->left, sum-root->val);
ans.pop_back();
}
if(root!=NULL&&root->right!= NULL )
{
pathSum1(root->right, sum - root->val);
ans.pop_back();
}
}
};