path-sum-ii leetcode C++
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 andsum = 22, 5 /
4 8 / /
11 13 4 / \ /
7 2 5 1 return
[ [5,4,11,2], [5,8,4,5] ]
C++
/**
* 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>> dp;
vector<int> path;
getPath(root,sum,dp,path);
return dp;
}
void getPath(TreeNode *root, int sum,vector<vector<int>>& dp,vector<int> path){
if(NULL == root) return;
path.push_back(root->val);
if(NULL == root->left && NULL == root->right && root->val == sum )
dp.push_back(path);
getPath(root->left,sum - root->val,dp,path);
getPath(root->right,sum - root->val,dp,path);
}
};