Skip to content

Commit f985998

Browse files
authored
Create Path-Sum-II.cpp
Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where the sum of the node values in the path equals targetSum. Each path should be returned as a list of the node values, not node references. A root-to-leaf path is a path starting from the root and ending at any leaf node. A leaf is a node with no children.
1 parent 38a5028 commit f985998

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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

Comments
 (0)