Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * 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>> res;
- vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
- vector<int> path;
- int currSum=0;
- dfs(root, path, currSum, targetSum);
- return res;
- }
- void dfs(TreeNode* root, vector<int> &path, int currSum, int targetSum){
- if(!root) return;
- path.push_back(root->val);
- currSum += root->val;
- if(!(root->left) && !(root->right) && currSum == targetSum){
- res.push_back(path);
- }
- else{
- dfs(root->left, path, currSum, targetSum);
- dfs(root->right, path, currSum, targetSum);
- }
- currSum -= root->val;
- path.pop_back();
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement