Bird
Raised Fist0
Interview Prepbinary-search-treesmediumAmazonFacebookMicrosoftBloomberg

BST Iterator (In-Order Next)

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize Iterator with root node

The iterator is initialized with the root node (7). The current pointer is set to root, and _advance() is called to find the first next_val.

💡 Initialization sets up the traversal starting point and prepares the first next value for immediate retrieval.
Line:self.current = root self.next_val = None self._advance()
💡 The iterator is ready to start traversal from the root, with next_val unset until _advance finds the first node.
📊
BST Iterator (In-Order Next) - Watch the Algorithm Execute, Step by Step
Watching this step-by-step reveals how the iterator efficiently finds the next smallest element by temporarily modifying the tree structure, which is hard to grasp from code alone.
Step 1/19
·Active fill★Answer cell
Current node: 1
7315920
DFS Stack
1 (entered)
Current node: 1
7315920
DFS Stack
1 (entered)pre=null
Current node: 1
7315920
DFS Stack
1 (entered)pre=2
Current node: 2
7315920
DFS Stack
2 (entered)
Current node: 1
7315920
Current node: 1
7315920
DFS Stack
1 (entered)
Return: 3
Current node: 1
7315920
DFS Stack
1 (entered)pre=2
Current node: 3
7315920
Current node: 3
7315920
DFS Stack
3 (entered)
Return: 7
Current node: 3
7315920
DFS Stack
3 (entered)pre=4
Current node: 4
7315920
DFS Stack
4 (entered)
Current node: 3
7315920
Current node: 3
7315920
DFS Stack
3 (entered)
Return: 9
Current node: 3
7315920
DFS Stack
3 (entered)pre=4
Current node: 5
7315920
Current node: 5
7315920
DFS Stack
5 (entered)
Return: 15
7315920
7315920
Return: 20
7315920
Return: false

Key Takeaways

✓ Morris traversal uses temporary threads to traverse BST in-order without extra space.

This is hard to see from code alone because the tree is modified and restored dynamically.

✓ The iterator always keeps the next smallest element ready in next_val for O(1) next() calls.

Understanding this precomputation clarifies why next() is efficient and immediate.

✓ Thread creation and removal correspond to moving down left subtrees and returning to parent nodes.

Seeing these steps visually reveals the traversal order and how the algorithm avoids recursion or stack.

Practice

(1/5)
1. Consider the following code snippet implementing the optimal iterative approach to convert a BST to a Greater Tree. Given the BST with nodes [2, 1, 3], what is the value of the root node after the function completes?
easy
A. 5
B. 6
C. 3
D. 4

Solution

  1. Step 1: Trace reverse inorder traversal order

    Nodes visited in order: 3, 2, 1.
  2. Step 2: Accumulate sums and update nodes

    acc_sum=0 initially. - Visit 3: acc_sum=3, node.val=3 - Visit 2: acc_sum=3+2=5, node.val=5 - Visit 1: acc_sum=5+1=6, node.val=6 Root node was 2, updated to 5.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Root node value after update is 5 [OK]
Hint: Reverse inorder sums nodes from largest to smallest [OK]
Common Mistakes:
  • Confusing traversal order and updating nodes too early
  • Off-by-one errors in accumulating sums
  • Misidentifying which node is root after updates
2. Given the following code for deleting a node in a BST, what is the value of root.val after calling deleteNode(root, 3) on the BST constructed by inserting nodes in order: 5, 3, 6?
easy
A. 6
B. 5
C. 3
D. null (root deleted)

Solution

  1. Step 1: Construct BST and locate node 3

    BST: root=5, left=3, right=6. Node with value 3 is a leaf (no children).
  2. Step 2: Delete node 3

    Since node 3 has no children, deletion returns null for root.left. Root remains 5 with left child null and right child 6.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Root value unchanged at 5 after deleting leaf 3 [OK]
Hint: Deleting leaf node returns null for that subtree [OK]
Common Mistakes:
  • Confusing root with deleted node
  • Replacing root value incorrectly
  • Assuming root is deleted
3. Consider the following buggy code for inserting a value into a BST. Which line contains the subtle bug that causes the insertion to fail silently in some cases?
def insertIntoBST(root, val):
    if root is None:
        return TreeNode(val)
    if val < root.val:
        insertIntoBST(root.left, val)
    else:
        insertIntoBST(root.right, val)
    return root
medium
A. Line 2: if root is None
B. Line 4: if val < root.val
C. Line 7: insertIntoBST(root.right, val)
D. Line 5: insertIntoBST(root.left, val)

Solution

  1. Step 1: Analyze recursive calls

    Recursive calls to insertIntoBST on root.left or root.right do not update the parent's child pointer.
  2. Step 2: Identify missing assignment

    Lines 5 and 7 call insertIntoBST but do not assign the returned subtree back to root.left or root.right, so insertion is lost.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Missing assignment causes silent insertion failure [OK]
Hint: Recursive insert must assign returned subtree to parent's child [OK]
Common Mistakes:
  • Not updating parent's child pointer
  • Confusing base case with recursive step
  • Incorrect comparison operator
4. The following code attempts to search for a value in a BST. Identify the line containing the subtle bug that can cause incorrect behavior or inefficiency.
def searchBST(root, val):
    if root is None:
        return None
    if root.val == val:
        return root
    left_search = searchBST(root.left, val)
    if left_search is not None:
        return left_search
    return searchBST(root.right, val)
medium
A. Line 5: left_search = searchBST(root.left, val)
B. Line 4: if root.val == val: return root
C. Line 2: if root is None: return None
D. Line 7: return searchBST(root.right, val)

Solution

  1. Step 1: Understand the code logic

    This code searches both left and right subtrees regardless of BST property.
  2. Step 2: Identify inefficiency bug

    Line 5 always searches left subtree even if val > root.val, ignoring BST property and causing O(n) time.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Ignoring BST property causes unnecessary subtree searches [OK]
Hint: Searching both subtrees ignores BST property [OK]
Common Mistakes:
  • Not pruning search using BST property
5. The following code attempts to find if there exist two distinct nodes in a BST whose values sum to k. Identify the line containing the subtle bug that can cause incorrect results.
medium
A. Line 6: dfs(node.left)
B. Line 4: if k - node.val in seen:
C. Line 7: seen.add(node.val)
D. Line 8: dfs(node.right)

Solution

  1. Step 1: Understand DFS and set usage

    The code checks if complement exists in seen before adding current node's value.
  2. Step 2: Identify bug in order of operations

    Checking complement before adding current node's value misses pairs where both nodes are the same, or misses valid pairs if current node's value is needed for complement checks in children.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Complement check must happen after adding current node's value to seen [OK]
Hint: Add current node to set before checking complements [OK]
Common Mistakes:
  • Checking complement before adding current node's value
  • Not handling None nodes properly
  • Returning False too early
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