Path Sum II
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 {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int> > res;
vector<int> solution;
dfs(root, sum, solution, res);
return res;
}
private:
void dfs(TreeNode *r,int gap, vector<int> &path, vector<vector<int> > &ret){
if(r == NULL){
//不在这里push_back的原因知道吗,是因为此时
//如果叶子节点满足条件了,会继续遍历叶子节点的
//两个孩子节点,都是NULL,这样就会重复
//if(gap == 0) ret.push_back(path);
return;
}
path.push_back(r->val);
if(r->left == NULL && r->right == NULL){
if(gap == r->val)
ret.push_back(path);
}
//只有到达NULL节点才会返回
dfs(r->left, gap-r->val, path, ret);
dfs(r->right, gap-r->val, path, ret);
path.pop_back();
}
};