Controlled in-order stack
Time O(1) amortised per call Space O(h)Constructor pushes the left spine. next() pops a node, pushes the left spine of its right child, returns the value. hasNext() checks the stack.
import java.util.ArrayDeque;
import java.util.Deque;
class BSTIterator {
private final Deque<TreeNode> stack = new ArrayDeque<>();
public BSTIterator(TreeNode root) { pushLeft(root); }
public int next() {
TreeNode n = stack.pop();
pushLeft(n.right);
return n.val;
}
public boolean hasNext() { return !stack.isEmpty(); }
private void pushLeft(TreeNode n) {
for (; n != null; n = n.left) stack.push(n);
}
}Verdict: Each node is pushed and popped exactly once overall.