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 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 {
private:
vector<vector<int>> result;
public:
void pathPlus(TreeNode * root, int sum, vector<int> &vec)
{
if(root->left==NULL && root->right==NULL)
{
vector<int>::iterator iter = vec.begin();
int totalsum = 0;
for( ; iter != vec.end() ; iter++)
{
totalsum += *iter;
}
if(totalsum == (sum-root->val))
{
vec.push_back(root->val);
result.push_back(vec);
vec.pop_back();
}
return;
}
cout<<root->val<<endl;
vec.push_back(root->val);
if(root->left)
pathPlus(root->left, sum, vec);
if(root->right)
pathPlus(root->right, sum, vec);
vec.pop_back();
}
void pathMinus(TreeNode * root, int sum, vector<int> &vec)
{
if(root->left==NULL && root->right==NULL && sum == root->val)
{
vec.push_back(root->val);
result.push_back(vec);
vec.pop_back();
return;
}
cout<<root->val<<endl;
vec.push_back(root->val);
if(root->left)
pathMinus(root->left, sum-root->val, vec);
if(root->right)
pathMinus(root->right, sum-root->val, vec);
vec.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if (root == NULL)
return vector<vector<int>>();
vector<int> vec;
pathPlus(root, sum, vec);
return result;
}
};