Using DFS, target will be target - root->val, remember to pop_back current vector;
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root the root of binary tree
* @param target an integer
* @return all valid paths
*/
vector<vector<int>> binaryTreePathSum(TreeNode *root, int target) {
// Write your code here
vector<vector<int>> results;
vector<int> cur;
dfsHelper(root, target, cur, results);
return results;
}
void dfsHelper(TreeNode* root, int target, vector<int>& cur, vector<vector<int>>& results) {
if (root == NULL) {
return;
}
cur.push_back(root->val);
if (root->left == NULL && root->right == NULL && root->val == target) {
results.push_back(cur);
}
else {
target = target - root->val;
}
dfsHelper(root->left, target, cur, results);
dfsHelper(root->right, target, cur, results);
cur.pop_back();
}
};