# [leetcode] Path Sum II

### 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 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) {
vector<vector<int> >re;
vector<int > thisRe;
_pathSum(root, sum, re, thisRe);
return re;
}
void _pathSum(TreeNode * root, int sum, vector<vector<int>>&re, vector<int>& thisRe){
if(root == NULL) return ;
if(sum - root->val == 0 && root->left == NULL && root->right == NULL){
thisRe.push_back(root->val);
re.push_back(thisRe);
thisRe.pop_back();
return ;
}
else{
thisRe.push_back(root->val);
_pathSum(root->left, sum - root->val, re, thisRe);
_pathSum(root->right, sum - root->val, re, thisRe);
thisRe.pop_back();
}
}
};```

This site uses Akismet to reduce spam. Learn how your comment data is processed.