Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the stack in the BST iterator constructor.
DSA C
void bstIteratorInit(BSTIterator* iter, TreeNode* root) {
iter->stack = createStack();
TreeNode* current = root;
while (current != NULL) {
stackPush(iter->stack, [1]);
current = current->left;
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Pushing current->left instead of current causes skipping nodes.
Pushing root repeatedly instead of current causes infinite loop.
✗ Incorrect
We push the current node itself onto the stack to traverse the leftmost path.
2fill in blank
mediumComplete the code to check if the BST iterator has a next smallest element.
DSA C
bool bstIteratorHasNext(BSTIterator* iter) {
return [1];
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning true when stack is empty causes wrong hasNext result.
Checking iter == NULL instead of stack emptiness.
✗ Incorrect
If the stack is not empty, there is a next smallest element.
3fill in blank
hardFix the error in the bstIteratorNext function to correctly return the next smallest value.
DSA C
int bstIteratorNext(BSTIterator* iter) {
TreeNode* node = stackPop(iter->stack);
int result = node->val;
node = node->right;
while (node != NULL) {
stackPush(iter->stack, [1]);
node = node->left;
}
return result;
}Attempts:
3 left
💡 Hint
Common Mistakes
Pushing node->right causes infinite loop or wrong traversal.
Pushing result (int) instead of node pointer causes type errors.
✗ Incorrect
We push the current node pointer to traverse its left subtree.
4fill in blank
hardFill both blanks to complete the stack push and pop operations in the BST iterator.
DSA C
void stackPush(Stack* stack, [1] value) { Node* newNode = malloc(sizeof(Node)); newNode->value = value; newNode->next = stack->top; stack->top = newNode; } [2] stackPop(Stack* stack) { if (stack->top == NULL) return NULL; Node* temp = stack->top; [3] value = temp->value; stack->top = temp->next; free(temp); return value; }
Attempts:
3 left
💡 Hint
Common Mistakes
Using int type causes type mismatch errors.
Using void as return type for pop causes missing return value.
✗ Incorrect
The stack stores TreeNode pointers, so push and pop use TreeNode* type.
5fill in blank
hardFill all three blanks to complete the BST iterator next function with correct stack operations and return value.
DSA C
int bstIteratorNext(BSTIterator* iter) {
TreeNode* node = [1](iter->stack);
int val = node->val;
node = node->right;
while (node != NULL) {
[2](iter->stack, node);
node = node->left;
}
return [3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using stackTop instead of stackPop causes infinite loop.
Returning node instead of val causes wrong return type.
✗ Incorrect
Pop the top node, push left children of right subtree, and return the node's value.
