/**
* 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>> result;
vector<int> subPath;
if (root) {
calculatePathSum(root, sum, subPath, 0, result);
}
return result;
}
void calculatePathSum(TreeNode* node, int sum, vector<int>& subPath, int subSum, vector<vector<int>>& result) {
subPath.push_back(node->val);
subSum += node->val;
if (!node->left && !node->right) {
if (sum == subSum) {
result.push_back(subPath);
}
}
if (node->left) {
calculatePathSum(node->left, sum, subPath, subSum, result);
}
if (node->right) {
calculatePathSum(node->right, sum, subPath, subSum, result);
}
subSum -= node->val;
subPath.pop_back();
}
};