-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path112. Path Sum.cpp
More file actions
44 lines (43 loc) · 792 Bytes
/
Copy path112. Path Sum.cpp
File metadata and controls
44 lines (43 loc) · 792 Bytes
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
#include"Inc.h"
class Solution {
public:
bool CheckPath(stack<TreeNode*> s, int sum) {
if (s.empty() && sum != 0) return true;
int path = 0;
while (!s.empty()) {
path += s.top()->val;
s.pop();
}
if (path == sum) return true;
else return false;
}
bool hasPathSum(TreeNode* root, int sum) {
stack<TreeNode*> poststack;
TreeNode* p, *pre;
p = root;
pre = NULL;
while (p) {
poststack.push(p);
p = p->left;
}
while (!poststack.empty()) {
p = poststack.top();
if (!p->right || p->right == pre) {
if (!p->left&&!p->right) {
if (CheckPath(poststack, sum))
return true;
}
pre = p;
poststack.pop();
}
else {
p = p->right;
while (p) {
poststack.push(p);
p = p->left;
}
}
}
return false;
}
};