Skip to content

Commit bf1111e

Browse files
Update and rename path_sum_2.cpp to path_sum_ii.cpp
1 parent 949308c commit bf1111e

File tree

2 files changed

+48
-35
lines changed

2 files changed

+48
-35
lines changed

path_sum_2.cpp

Lines changed: 0 additions & 35 deletions
This file was deleted.

path_sum_ii.cpp

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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+
//final ds
15+
vector<vector<int>> result;
16+
17+
//intermediary ds to check if current path is a 'path sum'
18+
vector<int> current_path;
19+
20+
//recursive method to find all root-to-leaf paths
21+
void helper(TreeNode* root, int sum) {
22+
23+
24+
//base case i
25+
if(!root) return;
26+
27+
current_path.push_back(root->val); //push current node in path and recurse for all the children emanting out of the path from current node i.e. root
28+
29+
//basecase ii
30+
if(!root->left && !root->right && root->val == sum) {
31+
result.push_back(current_path);
32+
}
33+
34+
else { //recurse for child nodes
35+
sum -= root->val;
36+
helper(root->left, sum);
37+
helper(root->right, sum);
38+
}
39+
40+
current_path.pop_back(); //remove current visited node
41+
}
42+
43+
vector<vector<int>> pathSum(TreeNode* root, int sum) {
44+
if(!root) return vector<vector<int>> ();
45+
helper(root, sum);
46+
return result;
47+
}
48+
};

0 commit comments

Comments
 (0)