|
| 1 | +// Time: O(n) |
| 2 | +// Space: O(n) |
| 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 | + bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) { |
| 16 | + Iterator<TreeNode*> left(root1, true), right(root2, false); |
| 17 | + while (*left && *right) { |
| 18 | + if ((*left)->val + (*right)->val < target) { |
| 19 | + ++left; |
| 20 | + } else if ((*left)->val + (*right)->val > target) { |
| 21 | + ++right; |
| 22 | + } else { |
| 23 | + return true; |
| 24 | + } |
| 25 | + } |
| 26 | + return false; |
| 27 | + } |
| 28 | + |
| 29 | +private: |
| 30 | + template<typename T> |
| 31 | + class Iterator { |
| 32 | + public: |
| 33 | + Iterator(T root, bool asc) |
| 34 | + : stack_{{root, false}} |
| 35 | + , asc_{asc} |
| 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 | + if (asc_) { |
| 52 | + stack_.emplace_back(root->right, false); |
| 53 | + stack_.emplace_back(root, true); |
| 54 | + stack_.emplace_back(root->left, false); |
| 55 | + } else { |
| 56 | + stack_.emplace_back(root->left, false); |
| 57 | + stack_.emplace_back(root, true); |
| 58 | + stack_.emplace_back(root->right, false); |
| 59 | + } |
| 60 | + } |
| 61 | + curr_ = T{}; |
| 62 | + return *this; |
| 63 | + } |
| 64 | + |
| 65 | + const T& operator*() const { |
| 66 | + return curr_; |
| 67 | + } |
| 68 | + |
| 69 | + private: |
| 70 | + vector<pair<T, bool>> stack_; |
| 71 | + bool asc_; |
| 72 | + T curr_; |
| 73 | + }; |
| 74 | +}; |
0 commit comments