File tree 1 file changed +67
-0
lines changed
1 file changed +67
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n)
2
+ // Space: O(h)
3
+
4
+ /* *
5
+ * Definition for a binary tree node.
6
+ * struct TreeNode {
7
+ * int val;
8
+ * TreeNode *left;
9
+ * TreeNode *right;
10
+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
11
+ * };
12
+ */
13
+ class Solution {
14
+ public:
15
+ vector<int > getAllElements (TreeNode* root1, TreeNode* root2) {
16
+ vector<int > result;
17
+ Iterator<TreeNode*> left (root1), right (root2);
18
+ while (*left || *right) {
19
+ if (!*right || ((*left) && (*left)->val < (*right)->val )) {
20
+ result.emplace_back ((*left)->val );
21
+ ++left;
22
+ } else {
23
+ result.emplace_back ((*right)->val );
24
+ ++right;
25
+ }
26
+ }
27
+ return result;
28
+ }
29
+
30
+ private:
31
+ template <typename T>
32
+ class Iterator {
33
+ public:
34
+ Iterator (T root)
35
+ : stack_{{root, false }}
36
+ , curr_{} {
37
+ ++(*this );
38
+ }
39
+
40
+ Iterator& operator ++() {
41
+ while (!stack_.empty ()) {
42
+ T root; bool is_visited;
43
+ tie (root, is_visited) = stack_.back (); stack_.pop_back ();
44
+ if (!root) {
45
+ continue ;
46
+ }
47
+ if (is_visited) {
48
+ curr_ = root;
49
+ return *this ;
50
+ }
51
+ stack_.emplace_back (root->right , false );
52
+ stack_.emplace_back (root, true );
53
+ stack_.emplace_back (root->left , false );
54
+ }
55
+ curr_ = T{};
56
+ return *this ;
57
+ }
58
+
59
+ const T& operator *() const {
60
+ return curr_;
61
+ }
62
+
63
+ private:
64
+ vector<pair<T, bool >> stack_;
65
+ T curr_;
66
+ };
67
+ };
You can’t perform that action at this time.
0 commit comments