Skip to content

Commit b6ff4c7

Browse files
authoredSep 18, 2023
113. Path Sum 2
1 parent c1c52df commit b6ff4c7

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
 

‎113. Path Sum 2

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
void solve(TreeNode* root,int targetSum,int &currsum,vector<int>&path, vector<vector<int>>&ans){
2+
if(root == NULL){
3+
return;
4+
}
5+
//leaf node
6+
if(root->left == NULL && root->right == NULL){
7+
path.push_back(root->val);
8+
currsum += root->val;
9+
if(currsum == targetSum){
10+
ans.push_back(path);
11+
}
12+
//exceptional
13+
path.pop_back();
14+
currsum -= root->val;
15+
return;
16+
}
17+
//include curr node
18+
path.push_back(root->val);
19+
currsum += root->val;
20+
21+
solve(root->left,targetSum,currsum,path,ans);
22+
solve(root->right,targetSum,currsum,path,ans);
23+
24+
//exceptional backtrack, aslo can be done without this
25+
path.pop_back();
26+
currsum -= root->val;
27+
28+
}
29+
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
30+
vector<vector<int>>ans;
31+
int sum =0;
32+
vector<int>path;
33+
solve(root,targetSum, sum ,path,ans);
34+
return ans;
35+
36+
}

0 commit comments

Comments
 (0)
Please sign in to comment.