题目:
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 andsum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
程序:
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int>> res;
if(root==NULL)
return res;
solve(res,root,sum);
return res;
}
void solve(vector<vector<int>> &res,TreeNode *root,int sum)
{
if(root&&root->left==NULL&&root->right==NULL&&sum==root->val)
{
v.push_back(root->val);
res.push_back(v);
v.pop_back();
return;
}
if(root==NULL)
return;
v.push_back(root->val);
solve(res,root->left,sum-root->val);
solve(res,root->right,sum-root->val);
v.pop_back();
}
vector<int> v;
};