forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
all-elements-in-two-binary-search-trees.cpp
67 lines (62 loc) · 1.67 KB
/
all-elements-in-two-binary-search-trees.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:
vector<int> getAllElements(TreeNode* root1, TreeNode* root2) {
vector<int> result;
Iterator<TreeNode*> left(root1), right(root2);
while (*left || *right) {
if (!*right || ((*left) && (*left)->val < (*right)->val)) {
result.emplace_back((*left)->val);
++left;
} else {
result.emplace_back((*right)->val);
++right;
}
}
return result;
}
private:
template<typename T>
class Iterator {
public:
Iterator(T root)
: stack_{{root, false}}
, 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;
}
stack_.emplace_back(root->right, false);
stack_.emplace_back(root, true);
stack_.emplace_back(root->left, false);
}
curr_ = T{};
return *this;
}
const T& operator*() const {
return curr_;
}
private:
vector<pair<T, bool>> stack_;
T curr_;
};
};