forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
two-sum-iv-input-is-a-bst.cpp
67 lines (61 loc) · 1.49 KB
/
two-sum-iv-input-is-a-bst.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Time: O(n)
// Space: O(h)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
if (!root) {
return false;
}
BSTIterator left(root, true), right(root, false);
while (*left < *right) {
if (*left + *right == k) {
return true;
} else if (*left + *right < k) {
++left;
} else {
++right;
}
}
return false;
}
private:
class BSTIterator {
public:
BSTIterator(TreeNode *root, bool forward) :
node_(root),
forward_(forward) {
++(*this);
};
int operator*() {
return cur_;
}
void operator++() {
while (node_ || !s_.empty()) {
if (node_) {
s_.emplace(node_);
node_ = forward_ ? node_->left : node_->right;
} else {
node_ = s_.top();
s_.pop();
cur_ = node_->val;
node_ = forward_ ? node_->right : node_->left;
break;
}
}
}
private:
TreeNode* node_;
bool forward_;
stack<TreeNode*> s_;
int cur_;
};
};