- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 52 lines of C++ from the credited upstream file 1214.cpp.
- The implementation keeps its working state in language-native values and containers.
- 2 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class BSTIterator {2 public:3 BSTIterator(TreeNode* root, bool leftToRight) : leftToRight(leftToRight) {4 pushUntilNull(root);5 }6 7 bool hasNext() {8 return !stack.empty();9 }10 11 int next() {12 TreeNode* root = stack.top();13 stack.pop();14 pushUntilNull(leftToRight ? root->right : root->left);15 return root->val;16 }17 18 private:19 stack<TreeNode*> stack;20 bool leftToRight;21 22 void pushUntilNull(TreeNode* root) {23 while (root != nullptr) {24 stack.push(root);25 root = leftToRight ? root->left : root->right;26 }27 }28};29 30class Solution {31 public:32 bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) {33 BSTIterator bst1(root1, true);34 BSTIterator bst2(root2, false);35 36 for (int l = bst1.next(), r = bst2.next(); true;) {37 const int sum = l + r;38 if (sum == target)39 return true;40 if (sum < target) {41 if (!bst1.hasNext())42 return false;43 l = bst1.next();44 } else {45 if (!bst2.hasNext())46 return false;47 r = bst2.next();48 }49 }50 }51};52