173. Binary Search Tree Iterator
Problem
Design BSTIterator(root), which walks a BST in sorted (in-order) order: next() returns the next smallest value and hasNext() says whether any remain.
Example: [7,3,15,null,null,9,20] → next() returns 3, 7, 9, 15, 20
Constraints: follow-up: O(1) amortised per call using O(h) memory.
Controlled in-order traversal: stack holds the path of left children. next() pops, then pushes the left spine of its right child. Amortized O(1), O(h) memory.
Complexity: O(1) amortized per call, O(h) space.
class BSTIterator:
def __init__(self, root: Optional[TreeNode]):
self.st = []
self._push_left(root)
def _push_left(self, node):
while node:
self.st.append(node)
node = node.left
def next(self) -> int:
node = self.st.pop()
self._push_left(node.right)
return node.val
def hasNext(self) -> bool:
return bool(self.st)
it = BSTIterator(make_tree([7, 3, 15, None, None, 9, 20]))
out = []
while it.hasNext():
out.append(it.next())
assert out == [3, 7, 9, 15, 20]
it = BSTIterator(make_tree([1]))
assert it.hasNext() and it.next() == 1 and not it.hasNext()
class BSTIterator {
private final Deque<TreeNode> st = new ArrayDeque<>();
public BSTIterator(TreeNode root) { pushLeft(root); }
private void pushLeft(TreeNode n) { for (; n != null; n = n.left) st.push(n); }
public int next() {
TreeNode n = st.pop();
pushLeft(n.right);
return n.val;
}
public boolean hasNext() { return !st.isEmpty(); }
}
type BSTIterator struct {
st []*TreeNode // the path of left children still to visit
}
func Constructor(root *TreeNode) BSTIterator {
it := BSTIterator{}
it.pushLeft(root)
return it
}
func (this *BSTIterator) pushLeft(node *TreeNode) {
for ; node != nil; node = node.Left {
this.st = append(this.st, node)
}
}
func (this *BSTIterator) Next() int {
node := this.st[len(this.st)-1]
this.st = this.st[:len(this.st)-1]
this.pushLeft(node.Right)
return node.Val
}
func (this *BSTIterator) HasNext() bool {
return len(this.st) > 0
}