Approach
Stack-based processing
For Binary Search Tree Iterator II, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- Push the current item with only the information later steps need.
Code notes
- 39 lines of Java from the credited upstream file 1586.java.
- The implementation visibly relies on work queue.
- 1 loop block detected.
Complexity
If each item is pushed and popped at most once, the stack work is linear.
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 BSTIterator(TreeNode root) {3 pushLeftsUntilNull(root);4 }5 6 public boolean hasNext() {7 return !nexts.isEmpty();8 }9 10 public int next() {11 Pair<TreeNode, Boolean> pair = nexts.pop();12 TreeNode root = pair.getKey();13 boolean fromNext = pair.getValue();14 if (fromNext)15 pushLeftsUntilNull(root.right);16 prevsAndCurr.push(root);17 return root.val;18 }19 20 public boolean hasPrev() {21 return prevsAndCurr.size() > 1;22 }23 24 public int prev() {25 nexts.push(new Pair<>(prevsAndCurr.pop(), false));26 return prevsAndCurr.peek().val;27 }28 29 private void pushLeftsUntilNull(TreeNode root) {30 while (root != null) {31 nexts.push(new Pair<>(root, true));32 root = root.left;33 }34 }35 36 private Deque<TreeNode> prevsAndCurr = new ArrayDeque<>();37 private Deque<Pair<TreeNode, Boolean>> nexts = new ArrayDeque<>();38}39