Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
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 binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void pathSum(vector<vector<int> >& result,vector<int>& path,TreeNode* root,int sum){
path.push_back(root->val);
if(root->val==sum&&root->left==NULL&&root->right==NULL){//leaf node
result.push_back(path);
}
if(root->left&&root->left->val!='#'){
pathSum(result,path,root->left,sum-root->val);
}
if(root->right&&root->right->val!='#'){
pathSum(result,path,root->right,sum-root->val);
}
path.pop_back();
}
vector<vector<int> > pathSum(TreeNode* root,int sum) {
vector<vector<int> > result;
vector<int> path;
if(root==NULL){
return result;
}
pathSum(result,path,root,sum);
return result;
}
};