Skip to content

Commit 290291f

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <[email protected]>
1 parent 9eed79a commit 290291f

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

0113_path_sum_ii/path_sum.cc

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
#include <bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
/**
6+
* Definition for a binary tree node.
7+
* struct TreeNode {
8+
* int val;
9+
* TreeNode *left;
10+
* TreeNode *right;
11+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
12+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
13+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
14+
* };
15+
*/
16+
class Solution {
17+
public:
18+
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
19+
vector<vector<int>> res;
20+
dfs(root, targetSum, res);
21+
return res;
22+
}
23+
private:
24+
vector<int> stack;
25+
void dfs(TreeNode* root, int sum, vector<vector<int>>& res) {
26+
if (root == nullptr) {
27+
return;
28+
} else if (root->left == nullptr && root->right == nullptr && sum == root->val) {
29+
stack.push_back(root->val);
30+
res.push_back(stack);
31+
stack.pop_back();
32+
} else {
33+
stack.push_back(root->val);
34+
dfs(root->left, sum - root->val, res);
35+
dfs(root->right, sum - root->val, res);
36+
stack.pop_back();
37+
}
38+
}
39+
};

0 commit comments

Comments
 (0)