Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the stack in the BST iterator constructor.
DSA C#
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
TreeNode current = root;
while (current != null) {
stack.[1](current);
current = current.left;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using Pop instead of Push causes runtime errors.
Using Peek does not add elements to the stack.
✗ Incorrect
We use stack.Push(node) to add nodes to the stack while traversing left.
2fill in blank
mediumComplete the code to check if the iterator has more elements.
DSA C#
public bool HasNext() {
return stack.[1] > 0;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using Length or Size causes compile errors.
Using Capacity returns the allocated size, not the current count.
✗ Incorrect
Stack.Count returns the number of elements currently in the stack.
3fill in blank
hardFix the error in the Next() method to correctly return the next smallest element.
DSA C#
public int Next() {
TreeNode node = stack.[1]();
int result = node.val;
node = node.right;
while (node != null) {
stack.Push(node);
node = node.left;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using Peek returns the top element but does not remove it, causing infinite loops.
Using Push or Remove are invalid stack operations here.
✗ Incorrect
Pop removes and returns the top element from the stack, which is the next smallest node.
4fill in blank
hardFill both blanks to initialize the BST iterator and push all left children.
DSA C#
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
TreeNode [1] = root;
while ([2] != null) {
stack.Push([2]);
[2] = [2].left;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names inconsistently causes errors.
Using 'root' inside the loop without updating causes infinite loops.
✗ Incorrect
We use a variable named 'current' to traverse left nodes and push them onto the stack.
5fill in blank
hardFill all three blanks to implement the Next() method correctly.
DSA C#
public int Next() {
TreeNode [1] = stack.Pop();
int [2] = [1].val;
[3] = [1].right;
while (node != null) {
stack.Push(node);
node = node.left;
}
return [2];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using inconsistent variable names causes confusion.
Not updating the stack with right subtree nodes causes incorrect iteration.
✗ Incorrect
We pop the top node as 'node', store its value in 'result', then traverse its right subtree pushing left children.
