Practice
Solution
Step 1: Trace reverse inorder traversal order
Nodes visited in order: 3, 2, 1.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.Final Answer:
Option A -> Option AQuick Check:
Root node value after update is 5 [OK]
- Confusing traversal order and updating nodes too early
- Off-by-one errors in accumulating sums
- Misidentifying which node is root after updates
Solution
Step 1: Trace first tree (2,1,3)
Inorder traversal yields [1,2,3], strictly increasing, so returns true.Step 2: Trace second tree (5,1,4 with children 3 and 6)
Inorder traversal yields [1,5,3,4,6], 3 < 5 violates BST property, so returns false.Final Answer:
Option A -> Option AQuick Check:
First tree valid BST, second invalid due to subtree violation [OK]
- Assuming subtree root comparison is enough
- Confusing output order
- Missing strict inequality check
next() in the Morris traversal based BST Iterator, assuming the BST has n nodes?Solution
Step 1: Understand Morris traversal edge visits
Each edge in the BST is visited at most twice: once to create a thread and once to remove it.Step 2: Calculate amortized cost per next()
Since total work is O(n) for n nodes, and there are n calls to next(), average cost per call is O(1) amortized.Final Answer:
Option A -> Option AQuick Check:
Amortized O(1) per next() matches Morris traversal properties [OK]
- Assuming worst-case O(n) per call
- Confusing with stack-based O(h)
- Ignoring amortized analysis
Solution
Step 1: Analyze recursion calls
The algorithm visits each element exactly once to create a TreeNode, splitting the array into halves recursively.Step 2: Calculate total work
Each element is processed once, so total time is proportional to n.Final Answer:
Option B -> Option BQuick Check:
Single pass over array with divide-and-conquer -> O(n) time [OK]
- Confusing recursion depth with total work
- Assuming O(n log n) due to recursion
Solution
Step 1: Understand duplicates in BST
Duplicates can be on either left or right subtree depending on insertion rules, so pruning must consider equality carefully.Step 2: Adjust pruning for duplicates
When node.val equals low or high, both subtrees may contain duplicates within range, so both should be explored.Step 3: Avoid removing pruning entirely
Removing pruning loses efficiency; using a hash set is unnecessary as nodes are unique objects.Final Answer:
Option D -> Option DQuick Check:
Pruning adjusted for equality handles duplicates efficiently [OK]
- Removing pruning loses efficiency
- Assuming duplicates only on one side
