Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

BST Iterator Design in DSA Javascript - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
BST Iterator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of BST Iterator next() calls
Given the BST Iterator initialized with the BST below, what is the output sequence of calling next() three times?
DSA Javascript
class TreeNode {
  constructor(val, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

class BSTIterator {
  constructor(root) {
    this.stack = [];
    this._leftmostInorder(root);
  }

  _leftmostInorder(node) {
    while (node !== null) {
      this.stack.push(node);
      node = node.left;
    }
  }

  next() {
    const topNode = this.stack.pop();
    if (topNode.right !== null) {
      this._leftmostInorder(topNode.right);
    }
    return topNode.val;
  }

  hasNext() {
    return this.stack.length > 0;
  }
}

// BST structure:
//       7
//      / \
//     3   15
//         / \
//        9  20

const root = new TreeNode(7,
  new TreeNode(3),
  new TreeNode(15, new TreeNode(9), new TreeNode(20))
);
const iterator = new BSTIterator(root);

const output = [iterator.next(), iterator.next(), iterator.next()];
console.log(output);
A[3, 7, 9]
B[7, 3, 9]
C[3, 9, 7]
D[7, 9, 15]
Attempts:
2 left
💡 Hint
Remember, BST Iterator returns nodes in ascending order using in-order traversal.
🧠 Conceptual
intermediate
1:00remaining
Understanding BST Iterator hasNext() behavior
What does the hasNext() method of a BST Iterator indicate during iteration?
AIt returns true if the stack is empty.
BIt returns true if the current node has a right child.
CIt returns true if there are more nodes to visit in ascending order.
DIt returns true if the BST is balanced.
Attempts:
2 left
💡 Hint
Think about what the stack in the iterator represents.
🔧 Debug
advanced
1:30remaining
Identify the error in BST Iterator next() method
What error will occur when running the next() method in the following BST Iterator code snippet?
DSA Javascript
class BSTIterator {
  constructor(root) {
    this.stack = [];
    this._leftmostInorder(root);
  }

  _leftmostInorder(node) {
    while (node !== null) {
      this.stack.push(node);
      node = node.left;
    }
  }

  next() {
    const topNode = this.stack.pop();
    if (topNode.right !== null) {
      this._leftmostInorder(topNode.right);
    }
    return topNode.val;
  }

  hasNext() {
    return this.stack.length > 0;
  }
}

const iterator = new BSTIterator(null);
iterator.next();
ANo error, returns null
BTypeError: Cannot read property 'right' of undefined
CReferenceError: topNode is not defined
DRangeError: Maximum call stack size exceeded
Attempts:
2 left
💡 Hint
Consider what happens when the BST is empty and next() is called.
🚀 Application
advanced
0:45remaining
Number of next() calls to traverse entire BST
If a BST Iterator is initialized with a BST of 10 nodes, how many times must next() be called to visit all nodes?
A10
B9
C11
DDepends on the shape of the BST
Attempts:
2 left
💡 Hint
Each next() call returns one node's value.
🧠 Conceptual
expert
1:30remaining
Space complexity of BST Iterator
What is the worst-case space complexity of a BST Iterator implemented with a stack for a BST with n nodes?
AO(1), constant space
BO(n), where n is the number of nodes in the BST
CO(log n), assuming the BST is balanced
DO(h), where h is the height of the BST
Attempts:
2 left
💡 Hint
Consider how many nodes can be on the stack at once during traversal.

Practice

(1/5)
1. What is the main purpose of a BST Iterator in a binary search tree?
easy
A. To traverse the BST in ascending order without recursion
B. To insert new nodes into the BST
C. To delete nodes from the BST
D. To balance the BST automatically

Solution

  1. Step 1: Understand BST Iterator functionality

    A BST Iterator is designed to traverse the tree in sorted order, typically ascending, without using recursion.
  2. Step 2: Identify the main purpose

    It provides a way to get the next smallest element efficiently, which matches To traverse the BST in ascending order without recursion.
  3. Final Answer:

    To traverse the BST in ascending order without recursion -> Option A
  4. Quick Check:

    BST Iterator = Ascending traversal without recursion [OK]
Hint: BST Iterator returns next smallest element step-by-step [OK]
Common Mistakes:
  • Confusing iterator with insertion or deletion
  • Thinking it balances the tree automatically
  • Assuming it uses recursion internally
2. Which of the following is the correct way to initialize a BST Iterator class in JavaScript?
easy
A. function BSTIterator(root) { this.stack = []; this.pushRight(root); }
B. class BSTIterator { constructor(root) { this.stack = []; this.pushLeft(root); } }
C. class BSTIterator { constructor(root) { this.queue = []; this.pushLeft(root); } }
D. function BSTIterator(root) { this.queue = []; this.pushRight(root); }

Solution

  1. Step 1: Identify correct class syntax and initialization

    The BST Iterator is usually implemented as a class with a stack to store nodes and a helper method to push left children.
  2. Step 2: Check each option

    class BSTIterator { constructor(root) { this.stack = []; this.pushLeft(root); } } correctly uses a class, initializes a stack, and calls pushLeft on root. Others use queue or pushRight which are incorrect for BST Iterator.
  3. Final Answer:

    class BSTIterator { constructor(root) { this.stack = []; this.pushLeft(root); } } -> Option B
  4. Quick Check:

    Use stack and pushLeft in constructor [OK]
Hint: BST Iterator uses stack and pushLeft method [OK]
Common Mistakes:
  • Using queue instead of stack
  • Calling pushRight instead of pushLeft
  • Using function instead of class syntax
3. Given the BST below and the following code snippet, what will be the output? BST structure: ``` 7 / \ 3 15 / \ 9 20 ``` Code:
const iterator = new BSTIterator(root);
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.hasNext());
medium
A. [3, 7, false]
B. [7, 9, true]
C. [3, 7, true]
D. [9, 15, true]

Solution

  1. Step 1: Trace the first next() call

    First next() returns the smallest element, which is 3.
  2. Step 2: Trace the second next() call

    Second next() returns the next smallest, which is 7.
  3. Step 3: Check hasNext()

    After two next() calls, there are still nodes (9, 15, 20), so hasNext() returns true.
  4. Final Answer:

    [3, 7, true] -> Option C
  5. Quick Check:

    next() returns ascending nodes, hasNext() true if more nodes [OK]
Hint: next() returns next smallest; hasNext() true if stack not empty [OK]
Common Mistakes:
  • Assuming next() returns root first
  • Confusing hasNext() return value
  • Ignoring left subtree nodes
4. Consider this buggy BST Iterator method. What is the main error?
next() {
  const node = this.stack.pop();
  if (node.right) {
    this.pushRight(node.right);
  }
  return node.val;
}

pushRight(node) {
  while (node) {
    this.stack.push(node);
    node = node.right;
  }
}
medium
A. next() should not pop from stack
B. next() should return node.key instead of node.val
C. pushRight should use a queue instead of stack
D. pushRight should push left children, not right

Solution

  1. Step 1: Analyze pushRight method

    pushRight pushes right children, but BST Iterator needs to push left children to get next smallest.
  2. Step 2: Understand correct pushLeft usage

    Correct method pushes left children of right subtree to stack to maintain ascending order.
  3. Final Answer:

    pushRight should push left children, not right -> Option D
  4. Quick Check:

    Push left children to stack for correct order [OK]
Hint: Push left children of right subtree, not right children [OK]
Common Mistakes:
  • Pushing right children instead of left
  • Using queue instead of stack
  • Returning wrong node property
5. You want to design a BST Iterator that supports next() and hasNext() in O(1) average time and uses O(h) space, where h is tree height. Which approach best achieves this?
hard
A. Use a stack to store left children and push left nodes of right subtree on next()
B. Store all nodes in an array by inorder traversal at initialization
C. Use recursion to traverse nodes on each next() call
D. Use a queue to store nodes level by level

Solution

  1. Step 1: Understand time and space constraints

    O(1) average time per next() and O(h) space means no full traversal storage and no recursion per call.
  2. Step 2: Evaluate each approach

    Use a stack to store left children and push left nodes of right subtree on next() uses a stack to store left children and pushes left nodes of right subtree on next(), achieving O(1) average time and O(h) space. Store all nodes in an array by inorder traversal at initialization uses O(n) space. Use recursion to traverse nodes on each next() call uses recursion, not O(1) time. Use a queue to store nodes level by level uses queue level order, not inorder.
  3. Final Answer:

    Use a stack to store left children and push left nodes of right subtree on next() -> Option A
  4. Quick Check:

    Stack + push left children = O(1) avg time, O(h) space [OK]
Hint: Use stack with left children for efficient BST Iterator [OK]
Common Mistakes:
  • Storing all nodes wastes space
  • Using recursion causes slow next()
  • Using queue gives wrong traversal order
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard