Recall & Review
beginner
What is the main purpose of a BST Iterator?
A BST Iterator allows us to traverse a Binary Search Tree (BST) in sorted order (in-order traversal) one element at a time, without storing all elements at once.
Click to reveal answer
intermediate
How does a BST Iterator achieve O(h) space complexity, where h is the tree height?
It uses a stack to store nodes along the path from the root to the current node, pushing only left children. This stack size is at most the height of the tree, so space is O(h).
Click to reveal answer
beginner
In BST Iterator design, what does the next() method do?
The next() method returns the next smallest element in the BST by popping the top node from the stack and then pushing all left children of its right subtree.
Click to reveal answer
intermediate
Why do we push left children onto the stack during BST Iterator initialization and after calling next()?
Because in-order traversal visits left subtree first, pushing left children ensures the smallest elements are on top of the stack, ready to be returned next.
Click to reveal answer
advanced
What is the time complexity of the next() method in a BST Iterator over n calls?
Amortized time complexity is O(1) per call because each node is pushed and popped exactly once during the entire iteration.
Click to reveal answer
What data structure is commonly used inside a BST Iterator to track nodes?
✗ Incorrect
A stack is used to keep track of nodes along the path to the next smallest element.
What traversal order does a BST Iterator follow?
✗ Incorrect
BST Iterator returns elements in sorted order using in-order traversal.
What does the hasNext() method in a BST Iterator check?
✗ Incorrect
hasNext() returns true if there are still nodes to visit, which means the stack is not empty.
When next() is called, after popping a node, what nodes are pushed onto the stack?
✗ Incorrect
After popping, we push all left children of the right subtree to maintain in-order traversal.
What is the worst-case space complexity of a BST Iterator for a balanced BST?
✗ Incorrect
For a balanced BST, the height h is O(log n), so space complexity is O(h) = O(log n).
Explain how a BST Iterator uses a stack to return elements in sorted order.
Think about in-order traversal and how the stack helps track nodes.
You got /4 concepts.
Describe the time and space complexity of the BST Iterator and why it is efficient.
Consider how often nodes are pushed/popped and the maximum stack size.
You got /4 concepts.