|
| 1 | +/** |
| 2 | + * Definition for a binary tree node. |
| 3 | + * struct TreeNode { |
| 4 | + * int val; |
| 5 | + * TreeNode *left; |
| 6 | + * TreeNode *right; |
| 7 | + * TreeNode() : val(0), left(nullptr), right(nullptr) {} |
| 8 | + * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} |
| 9 | + * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} |
| 10 | + * }; |
| 11 | + */ |
| 12 | +class Solution { |
| 13 | +public: |
| 14 | + |
| 15 | + vector<vector<int>> res; //to store final result |
| 16 | + |
| 17 | + void traverse(TreeNode* root, vector <int> &path, int rem){ |
| 18 | + if(!root) return; //return at NULL |
| 19 | + |
| 20 | + if(!root->left && !root->right){ //leaf node reached |
| 21 | + path.push_back(root->val); //do |
| 22 | + if(rem == root->val) res.push_back(path); |
| 23 | + //if remaining sum is same as value of root we have valid path |
| 24 | + path.pop_back(); // undo |
| 25 | + return; |
| 26 | + } |
| 27 | + |
| 28 | + int val = root->val; //subtract the contribution of this value from rem (remaining sum) |
| 29 | + path.push_back(val); //do |
| 30 | + traverse(root->left, path, rem-val); //recurse left subtree |
| 31 | + traverse(root->right, path, rem-val); //recurse right subtree |
| 32 | + path.pop_back(); //undo |
| 33 | + |
| 34 | + } |
| 35 | + |
| 36 | + vector<vector<int>> pathSum(TreeNode* root, int targetSum) { |
| 37 | + res.clear(); //reset res |
| 38 | + if(!root) return res; //if root itself NULL there are no paths |
| 39 | + vector <int> path; //to store the path |
| 40 | + traverse(root, path, targetSum); |
| 41 | + return res; |
| 42 | + } |
| 43 | +}; |
0 commit comments