Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the stack in the BST Iterator constructor.
DSA Python
class BSTIterator: def __init__(self, root): self.stack = [] self._leftmost_inorder(root) def _leftmost_inorder(self, node): while node is not None: self.stack.[1](node) node = node.left
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop' instead of 'append' which removes elements.
Using 'remove' which deletes a specific element, not adding.
Using 'insert' without specifying index.
✗ Incorrect
We use 'append' to add nodes to the stack as we traverse left.
2fill in blank
mediumComplete the code to check if the iterator has a next smallest number.
DSA Python
def hasNext(self): return [1] > 0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'self.stack' directly which returns a list, not a boolean.
Using 'self.stack[-1]' which accesses the last element but does not check if stack is empty.
Using 'pop' which removes an element instead of checking.
✗ Incorrect
We check if the stack length is greater than zero to know if there is a next element.
3fill in blank
hardFix the error in the next() method to pop the top node from the stack.
DSA Python
def next(self): top_node = self.stack.[1]() if top_node.right is not None: self._leftmost_inorder(top_node.right) return top_node.val
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'append' which adds instead of removing.
Using 'remove' which deletes a specific element but does not return it.
Using 'insert' which adds elements at a position.
✗ Incorrect
We use 'pop' to remove and return the last element from the stack.
4fill in blank
hardFill both blanks to complete the _leftmost_inorder helper method for the BST Iterator.
DSA Python
def _leftmost_inorder(self, node): while node is not None: self.stack.[1](node) node = node.[2]
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'pop' instead of 'append' to add nodes.
Moving to the right child instead of left.
✗ Incorrect
We append nodes to the stack and move to the left child to reach the smallest node.
5fill in blank
hardFill all three blanks to complete the next() method that returns the next smallest value in the BST.
DSA Python
def next(self): top_node = self.stack.[1]() if top_node.[2] is not None: self._leftmost_inorder(top_node.[3]) return top_node.val
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'append' instead of 'pop' to get the top node.
Checking the left child instead of right.
Passing the left child to _leftmost_inorder instead of right.
✗ Incorrect
We pop the top node, check if it has a right child, and if so, traverse its leftmost nodes.
