/**************************************************************************
*
* 112. [Path Sum II](https://leetcode.com/problems/path-sum-ii/)
*
* Given the root of a binary tree and an integer targetSum,
* return all root-to-leaf paths where each path's sum equals targetSum.
* A leaf is a node with no children.
*
* Example:
* Given the below binary tree and sum = 22,
*
* 5
* / \
* 4 8
* / / \
* 11 13 4
* / \ \
* 7 2 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() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int> > pathSum(TreeNode* root, int targetSum) {
vector<vector<int> > result;
vector<int> cur;
sum(root, targetSum, result, cur);
return result;
}
void sum(TreeNode* root, int target, vector<vector<int> > &result, vector<int> &cur) {
if (nullptr == root) return;
cur.push_back(root->val);
if (nullptr == root->left && nullptr == root->right && target == root->val)
result.push_back(cur);
sum(root->left, target - root->val, result, cur);
sum(root->right,target - root->val, result, cur);
cur.pop_back();
}
};