struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
//record all the path, though dfs is not time efficient bu also work at most time
public:
void DFS(TreeNode* root, int curSum, vector<int> curPath, vector<vector<int>>& ansPath, int sum)
{
if(!root)
return;
curSum += root->val;
curPath.push_back(root->val);
if(!root->left && !root->right)
{
if(curSum == sum)
ansPath.push_back(curPath);
return;
}
DFS(root->left, curSum, curPath, ansPath, sum);
DFS(root->right, curSum, curPath, ansPath, sum);
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > ansPath;
vector<int> curPath;
DFS(root, 0, curPath, ansPath, sum);
return ansPath;
}
};
second time
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void pathSumUtil(TreeNode* root, int sum, int curSum, vector<int>& curPath, vector<vector<int> >& allPath)
{
if(root == NULL) return;
if(root->left == NULL && root->right == NULL)
{
if(curSum+root->val == sum)
{
curPath.push_back(root->val);
allPath.push_back(curPath);
curPath.pop_back();
}
return;
}
curPath.push_back(root->val);
pathSumUtil(root->left, sum, curSum+root->val, curPath, allPath);
curPath.pop_back();
curPath.push_back(root->val);
pathSumUtil(root->right, sum, curSum+root->val, curPath, allPath);
curPath.pop_back();
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> curPath;
vector<vector<int> > allPath;
pathSumUtil(root, sum, 0, curPath, allPath);
return allPath;
}
};