Practice
Solution
Step 1: Understand the problem constraints
The iterator must return elements in ascending order without storing all nodes upfront to save space.Step 2: Evaluate approaches
Full inorder traversal (B) uses O(n) space upfront, breadth-first (C) does not guarantee sorted order, and divide-and-conquer merging (D) is inefficient per next() call. Controlled inorder traversal with a stack (A) lazily fetches the next smallest element using O(h) space, which is optimal for this problem.Final Answer:
Option D -> Option DQuick Check:
Lazy stack-based inorder traversal matches the problem requirements [OK]
- Thinking BFS returns sorted order
- Assuming full traversal is always best
- Confusing divide-and-conquer with lazy iteration
s during the first iteration of the while loop?Solution
Step 1: Perform inorder traversal
Inorder traversal of BST yields sorted array: [2, 3, 4, 5, 6, 7]Step 2: Calculate s in first iteration
left=0 (value=2), right=5 (value=7), s = 2 + 7 = 9Final Answer:
Option A -> Option AQuick Check:
Sum matches target k=9 on first iteration [OK]
- Off-by-one error in indexing left or right
- Confusing node values with indices
- Miscomputing sum s
Solution
Step 1: Identify pointer reset necessity
When rebuilding, left and right pointers must be reset to avoid old links causing cycles.Step 2: Locate missing reset in code
Commented out line resetting node.left and node.right causes bug.Final Answer:
Option A -> Option AQuick Check:
Not resetting pointers -> cycles or incorrect tree [OK]
- Ignoring pointer reset leads to subtle bugs
- Misunderstanding traversal appending nodes is correct
- Thinking stack order affects correctness here
Solution
Step 1: Identify traversal path length
The algorithm moves from root down one path until the split point, visiting at most h nodes.Step 2: Understand h vs n
Height h can be up to n in worst case (skewed tree), but the question asks for optimal algorithm time complexity, which assumes balanced BST where h = log n.Final Answer:
Option A -> Option AQuick Check:
Traversal limited to one root-to-node path in balanced BST [OK]
- Confusing worst-case O(n) with average-case O(log n)
- Assuming constant time due to simple comparisons
- Ignoring that recursion stack space is not used here
Solution
Step 1: Understand duplicates in BST
Duplicates can be on left or right subtree depending on implementation; inclusive range means nodes equal to low or high must be kept.Step 2: Modify pruning conditions
Use <= and >= in comparisons to keep nodes equal to boundaries, ensuring duplicates within range remain.Step 3: Avoid rebuilding
Rebuilding wastes time and space; pruning with adjusted conditions preserves BST and duplicates correctly.Final Answer:
Option C -> Option CQuick Check:
Inclusive pruning keeps duplicates at boundaries [OK]
- Using strict inequalities excludes boundary duplicates
- Rebuilding unnecessarily wastes resources
