forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
two-sum-bsts.cpp
74 lines (69 loc) · 1.93 KB
/
two-sum-bsts.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
68
69
70
71
72
73
74
// Time: O(n)
// Space: O(n)
/**
* 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 twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) {
Iterator<TreeNode*> left(root1, true), right(root2, false);
while (*left && *right) {
if ((*left)->val + (*right)->val < target) {
++left;
} else if ((*left)->val + (*right)->val > target) {
++right;
} else {
return true;
}
}
return false;
}
private:
template<typename T>
class Iterator {
public:
Iterator(T root, bool asc)
: stack_{{root, false}}
, asc_{asc}
, curr_{} {
++(*this);
}
Iterator& operator++() {
while (!stack_.empty()) {
T root; bool is_visited;
tie(root, is_visited) = stack_.back(); stack_.pop_back();
if (!root) {
continue;
}
if (is_visited) {
curr_ = root;
return *this;
}
if (asc_) {
stack_.emplace_back(root->right, false);
stack_.emplace_back(root, true);
stack_.emplace_back(root->left, false);
} else {
stack_.emplace_back(root->left, false);
stack_.emplace_back(root, true);
stack_.emplace_back(root->right, false);
}
}
curr_ = T{};
return *this;
}
const T& operator*() const {
return curr_;
}
private:
vector<pair<T, bool>> stack_;
bool asc_;
T curr_;
};
};