Practice
Solution
Step 1: Trace first iteration with current=6
p=2 and q=8; 2 < 6 and 8 > 6, so current is split point; return 6.Step 2: Confirm no further traversal
Since p and q lie on different sides of 6, 6 is the LCA.Final Answer:
Option D -> Option DQuick Check:
Split point found at root 6 immediately [OK]
- Returning smaller node instead of split point
- Confusing left/right subtree traversal
- Off-by-one error in loop conditions
Solution
Step 1: Understand the problem constraints
The problem requires trimming nodes outside [low, high] while preserving BST properties efficiently.Step 2: Evaluate approaches
Rebuilding the tree (A) wastes time and space. Greedy removal (C) is inefficient and may break BST structure. DP (B) is unnecessary and overcomplicates. Iterative pruning (D) leverages BST properties to skip subtrees and adjust pointers in O(n) time and O(1) space.Final Answer:
Option A -> Option AQuick Check:
Iterative pruning uses BST properties optimally [OK]
- Rebuilding tree wastes space and time
- Greedy removal breaks BST structure
def insertIntoBST(root, val):
if root is None:
return TreeNode(val)
curr = root
while curr:
if val < curr.val:
if curr.left is None:
curr.left = TreeNode(val)
return root
curr = curr.left
else:
if curr.right is None:
curr.right = TreeNode(val)
return root
curr = curr.right
return root
Solution
Step 1: Identify traversal cost
Insertion requires traversing from root down to a leaf where the new node is inserted.Step 2: Relate traversal to tree height
In worst case, the tree is skewed, so height h can be up to n, but complexity is expressed as O(h).Final Answer:
Option B -> Option BQuick Check:
Traversal cost dominates insertion -> O(h) [OK]
- Assuming O(1) because insertion is at leaf
- Confusing height h with number of nodes n
- Assuming BST is always balanced
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
Solution
Step 1: Analyze recursive calls
Recursive calls to insertIntoBST on root.left or root.right do not update the parent's child pointer.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.Final Answer:
Option D -> Option DQuick Check:
Missing assignment causes silent insertion failure [OK]
- Not updating parent's child pointer
- Confusing base case with recursive step
- Incorrect comparison operator
Solution
Step 1: Understand BST height and search path
The search path length is at most the height h of the BST, as each step moves down one level.Step 2: Analyze worst-case time complexity
In worst case (unbalanced tree), h can be up to n, but complexity is expressed as O(h), not O(n) directly.Final Answer:
Option C -> Option CQuick Check:
Search complexity depends on tree height, not total nodes necessarily [OK]
- Assuming O(log n) always, ignoring unbalanced trees
