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 binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<vector<int> > res;
if(root == NULL)return res;
vector<int> curres;
curres.push_back(root->val);
pathSumRecur(root, sum, curres, res);
return res;
}
void pathSumRecur(TreeNode *root, int sum, vector<int> &curres, vector<vector<int> >&res)
{
if(root->left == NULL && root->right == NULL && root->val == sum)
{
res.push_back(curres);
return;
}
if(root->left)
{
curres.push_back(root->left->val);
pathSumRecur(root->left, sum - root->val, curres, res);
curres.pop_back();
}
if(root->right)
{
curres.push_back(root->right->val);
pathSumRecur(root->right, sum - root->val, curres, res);
curres.pop_back();
}
}
};