Practice
Solution
Step 1: Perform inorder traversal on BST with nodes 1, 2, 3
Inorder traversal yields nodes in sorted order: [1, 2, 3].Step 2: Iteratively build balanced BST choosing middle node
Middle index is 1 (0-based), so node with value 2 becomes root.Final Answer:
Option B -> Option BQuick Check:
Middle of [1,2,3] is 2 -> root value 2 [OK]
- Choosing left or right middle always, skewing tree
- Confusing preorder with inorder traversal results
- Forgetting to reset left/right pointers causing cycles
Solution
Step 1: Understand BST property
The BST property requires all left subtree nodes to be less than the current node and all right subtree nodes to be greater, strictly increasing in inorder traversal.Step 2: Recognize inorder traversal pattern
Inorder traversal of a valid BST produces a strictly increasing sequence of values, so verifying this sequence guarantees correctness efficiently.Final Answer:
Option D -> Option DQuick Check:
Inorder traversal yields sorted values for BST [OK]
- Only comparing node with immediate children
- Using greedy checks without global ordering
- Confusing subtree min/max with inorder sequence
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: Identify BST strict inequality
BST requires node.val to be strictly greater than previous inorder value; using < instead of <= allows duplicates.Step 2: Understand impact of bug
Using node.val < prev[0] misses the case when node.val == prev[0], incorrectly allowing duplicates and invalid BSTs.Final Answer:
Option C -> Option CQuick Check:
Strict inequality check is essential to reject duplicates [OK]
- Allowing duplicates by using < instead of <=
- Not resetting prev between calls
- Only comparing immediate children
Solution
Step 1: Understand duplicates in BST with relaxed property
Inorder traversal still produces nodes in non-decreasing order preserving duplicates order.Step 2: Rebuild balanced BST using middle node selection
Choosing middle node as root maintains balance and respects duplicates order.Step 3: Avoid sorting or preorder traversal
Sorting is unnecessary and preorder breaks sorted order; left middle bias skews balance.Final Answer:
Option C -> Option CQuick Check:
Inorder traversal + middle node rebuild works with duplicates [OK]
- Using preorder traversal losing sorted order
- Sorting nodes again causing unnecessary overhead
- Biasing middle index causing unbalanced tree
