Challenge - 5 Problems
BST Iterator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput 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 Java
class TreeNode { int val; TreeNode left, right; TreeNode(int x) { val = x; } } // BST structure: // 7 // / \ // 3 15 // / \ // 9 20 BSTIterator iterator = new BSTIterator(root); // root is the above tree System.out.print(iterator.next() + ", "); System.out.print(iterator.next() + ", "); System.out.print(iterator.next());
Attempts:
2 left
💡 Hint
Remember, BST Iterator returns elements in ascending order.
✗ Incorrect
The BST Iterator returns the next smallest element each time next() is called. The in-order traversal of the tree is 3, 7, 9, 15, 20. So the first three next() calls return 3, 7, and 9.
🧠 Conceptual
intermediateUnderstanding BST Iterator hasNext() behavior
If a BST Iterator is initialized with a BST containing nodes [5, 3, 7], and next() has been called twice, what will hasNext() return?
Attempts:
2 left
💡 Hint
Think about how many nodes remain after two next() calls.
✗ Incorrect
The BST has three nodes. After calling next() twice, one node remains unvisited. So hasNext() returns true.
🔧 Debug
advancedIdentify the bug in BST Iterator next() method
What error will occur when running the following next() method code snippet in a BST Iterator?
DSA Java
public int next() { TreeNode node = stack.pop(); if (node.right != null) { pushLeft(node.right); } return node.val; } private void pushLeft(TreeNode node) { while (node != null) { stack.push(node); node = node.left; } }
Attempts:
2 left
💡 Hint
Check how the stack is used and how pushLeft works.
✗ Incorrect
The code correctly pops the top node, pushes all left children of the right subtree, and returns the node's value. No errors occur if stack is managed properly.
❓ Predict Output
advancedOutput after full iteration of BST Iterator
What is the output of printing all elements using BST Iterator's next() until hasNext() returns false for the BST below?
DSA Java
// BST structure: // 10 // / \ // 5 15 // / \ \ // 3 7 18 BSTIterator iterator = new BSTIterator(root); while(iterator.hasNext()) { System.out.print(iterator.next() + " "); }
Attempts:
2 left
💡 Hint
BST Iterator returns nodes in ascending order.
✗ Incorrect
The in-order traversal of the BST is 3, 5, 7, 10, 15, 18. The iterator prints nodes in this order.
🧠 Conceptual
expertSpace complexity of BST Iterator
What is the worst-case space complexity of a BST Iterator implemented using a stack to simulate in-order traversal for a BST with n nodes?
Attempts:
2 left
💡 Hint
Consider how many nodes can be on the stack at once during traversal.
✗ Incorrect
The stack stores nodes along the path from root to the current node, which is at most the height h of the tree. So space complexity is O(h).
