Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the stack in the BST Iterator constructor.
DSA Java
public BSTIterator(TreeNode root) {
stack = new Stack<>();
[1](root);
}
private void pushLeft(TreeNode node) {
while (node != null) {
stack.push(node);
node = node.left;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using popLeft instead of pushLeft causes runtime errors.
Calling pushRight does not initialize the stack correctly.
✗ Incorrect
The constructor calls pushLeft(root) to push all left children onto the stack, preparing for in-order traversal.
2fill in blank
mediumComplete the code to check if the BST Iterator has a next element.
DSA Java
public boolean hasNext() {
return [1].isEmpty() == false;
}Attempts:
3 left
💡 Hint
Common Mistakes
Checking a queue or list instead of the stack.
Using isEmpty() without negation.
✗ Incorrect
The stack stores nodes to visit; if it's not empty, there is a next element.
3fill in blank
hardFix the error in the next() method to correctly return the next smallest element.
DSA Java
public int next() {
TreeNode node = stack.[1]();
pushLeft(node.right);
return node.val;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() returns the node but does not remove it, causing infinite loops.
Using push() or remove() causes errors.
✗ Incorrect
pop() removes and returns the top node from the stack, which is the next smallest element.
4fill in blank
hardFill both blanks to complete the pushLeft method that pushes all left children onto the stack.
DSA Java
private void pushLeft(TreeNode [1]) { while ([2] != null) { stack.push([2]); [2] = [2].left; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names causing undefined variable errors.
Using 'root' or 'current' inconsistently.
✗ Incorrect
The method uses 'node' as the parameter and iterates using the same variable to push left children.
5fill in blank
hardFill all three blanks to complete the next() method that returns the next smallest element and updates the stack.
DSA Java
public int next() {
TreeNode [1] = stack.[2]();
[3]([1].right);
return [1].val;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() instead of pop() causes infinite loops.
Not pushing left children of the right subtree.
✗ Incorrect
The method pops the top node as 'node', pushes its right child's left descendants, then returns its value.
