-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeepSearch.cpp
More file actions
42 lines (42 loc) · 1.24 KB
/
deepSearch.cpp
File metadata and controls
42 lines (42 loc) · 1.24 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
#include<stack>
using namespace std;
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:
bool hasPathSum(TreeNode* root, int targetSum) {
int sum = root->val;
stack<TreeNode*> s;
s.push(root);
while(s.size() > 0) {
while(s.top()->left != nullptr || s.top()->right!=nullptr) {
if (s.top()->left != nullptr) {
sum += s.top()->left->val;
s.push(s.top()->left);
}
else {
sum += s.top()->right->val;
s.push(s.top()->right);
}
}
if (sum == targetSum)
return true;
while(true) {
TreeNode* child = s.top();
sum -= child->val;
s.pop();
if (s.top() ->right != nullptr) {
s.push(s.top() ->right);
break;
}
}
}
return false;
}
};