-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path113. Path Sum II.cpp
52 lines (51 loc) · 974 Bytes
/
113. Path Sum II.cpp
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
#include"Inc.h"
class Solution {
public:
bool CalculateAndStore(vector<vector<int>> &ret, vector<int> &curr, stack<TreeNode*> sta, int sum) {
curr.clear();
int target = 0;
while (!sta.empty()) {
target += sta.top()->val;
curr.insert(curr.begin(), sta.top()->val);
sta.pop();
}
if (target == sum) {
ret.push_back(curr);
return true;
}
else {
curr.clear();
return false;
}
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> ret;
vector<int> curr;
if (!root) return ret;
stack<TreeNode*> sta;
TreeNode* p = root;
TreeNode* pre = NULL;
while (p) {
sta.push(p);
p = p->left;
}
while (!sta.empty()) {
p = sta.top();
if (!p->right || p->right == pre) {
if (!p->right&&!p->left) {
CalculateAndStore(ret, curr, sta, sum);
}
pre = p;
sta.pop();
}
else {
p = p->right;
while (p) {
sta.push(p);
p = p->left;
}
}
}
return ret;
}
};