- 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
- 49 lines of Java from the credited upstream file 1214.java.
- The implementation visibly relies on work queue.
- 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 BSTIterator(TreeNode root, boolean leftToRight) {3 this.leftToRight = leftToRight;4 pushUntilNull(root);5 }6 7 public boolean hasNext() {8 return !stack.isEmpty();9 }10 11 public int next() {12 TreeNode root = stack.pop();13 pushUntilNull(leftToRight ? root.right : root.left);14 return root.val;15 }16 17 private Deque<TreeNode> stack = new ArrayDeque<>();18 private boolean leftToRight;19 20 private void pushUntilNull(TreeNode root) {21 while (root != null) {22 stack.push(root);23 root = leftToRight ? root.left : root.right;24 }25 }26}27 28class Solution {29 public boolean twoSumBSTs(TreeNode root1, TreeNode root2, int target) {30 BSTIterator bst1 = new BSTIterator(root1, true);31 BSTIterator bst2 = new BSTIterator(root2, false);32 33 for (int l = bst1.next(), r = bst2.next(); true;) {34 final int sum = l + r;35 if (sum == target)36 return true;37 if (sum < target) {38 if (!bst1.hasNext())39 return false;40 l = bst1.next();41 } else {42 if (!bst2.hasNext())43 return false;44 r = bst2.next();45 }46 }47 }48}49