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:
void dfs_Path(TreeNode* node, int sum, int curSum, vector<int> path, vector<vector<int> > &pathSet){
if (node == NULL) return;
path.push_back(node->val);
curSum += node->val;
if(node->left == NULL && node->right == NULL){//到达叶节点
if(curSum == sum){//如果符合要求
pathSet.push_back(path);//保存
}
return;
}
dfs_Path(node->left, sum, curSum, path, pathSet);
dfs_Path(node->right, sum, curSum, path, pathSet);
}
vector<vector<int> > pathSum(TreeNode* root, int sum) {
vector<vector<int> > pathSet;
vector<int> path;
dfs_Path(root, sum, 0, path, pathSet);
return pathSet;
}
};