-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path113_Path_Sum_II.cpp
More file actions
62 lines (57 loc) · 1.19 KB
/
113_Path_Sum_II.cpp
File metadata and controls
62 lines (57 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <bits/stdc++.h>
using namespace std;
#define ll long long
// * Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
vector<vector<int>> res;
if (root == nullptr) return res;
stack<pair<TreeNode* , bool>> st;
TreeNode *node = root;
int sum = 0;
vector<int> temp;
bool flag = true;
while (flag)
{
if (node)
{
sum += node->val;
temp.push_back(node->val);
if (sum == targetSum && !(node->left) && !(node->right))
{
res.push_back(temp);
}
st.push({node, false});
node = node->left;
}
else if (!st.empty())
{
while (!st.empty() && st.top().second)
{
sum -= st.top().first->val;
temp.pop_back();
st.pop();
}
if (!st.empty())
{
node = st.top().first->right;
st.top().second = true;
}
}
else flag = false;
}
return res;
}
};
int main() {
return 0;
}