Practice
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def kthSmallest(root: Optional[TreeNode], k: int) -> int:
stack = []
current = root
count = 0
while current or stack:
while current:
stack.append(current)
current = current.left
current = stack.pop()
count += 1
if count == k:
return current.val
current = current.right
# Tree:
# 3
# / \
# 1 4
# \
# 2
root = TreeNode(3)
root.left = TreeNode(1)
root.right = TreeNode(4)
root.left.right = TreeNode(2)
print(kthSmallest(root, 2))
Solution
Step 1: Trace the inorder traversal steps
Stack initially empty, current=root(3). Push 3, move left to 1. Push 1, move left to None. Pop 1 (count=1), move right to 2.Step 2: Continue traversal to find kth=2
Push 2, move left None. Pop 2 (count=2), return 2 as kth smallest.Final Answer:
Option C -> Option CQuick Check:
Second smallest in BST is 2 [OK]
- Off-by-one counting of k
- Returning before incrementing count
Solution
Step 1: Understand the problem constraints
The problem requires recovering a BST where two nodes are swapped, without extra space and without changing the tree structure.Step 2: Identify the approach that meets constraints
Morris inorder traversal allows inorder traversal without recursion or stack, detecting swapped nodes on the fly and swapping their values, achieving O(1) space.Final Answer:
Option D -> Option DQuick Check:
Morris traversal is the only approach with O(1) space and no structural changes [OK]
- Assuming sorting values is optimal despite extra space
- Believing greedy single pass fixes all cases
- Confusing DP with tree recovery
Solution
Step 1: Analyze inorder traversal time
Inorder traversal visits each node once -> O(n).Step 2: Analyze balanced BST construction time
Rebuilding uses indices to pick middle nodes without extra sorting -> O(n).Step 3: Consider sorting complexity
Although inorder traversal produces sorted nodes, if sorting is mistakenly applied, complexity becomes O(n log n).Final Answer:
Option A -> Option AQuick Check:
Sorting nodes during traversal leads to O(n log n) [Trap]
- Assuming sorting is not needed, leading to O(n)
- Thinking recursive rebuild is O(n^2) due to repeated subtree calls
- Confusing traversal and construction complexities
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 DFS and set usage
The code checks if complement exists in seen before adding current node's value.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.Final Answer:
Option B -> Option BQuick Check:
Complement check must happen after adding current node's value to seen [OK]
- Checking complement before adding current node's value
- Not handling None nodes properly
- Returning False too early
