Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the k-th smallest key in a BST. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
Problem: Find the k-th smallest key in a BST. Trees are built by build(xs): a level-order list where index i has children 2i+1 and 2i+2 (None = no node).
class T:
def __init__(self, v, l=None, r=None):
self.v, self.l, self.r = v, l, r
def build(xs, i=0):
if i >= len(xs) or xs[i] is None: return None
return T(xs[i], build(xs, 2*i+1), build(xs, 2*i+2))
def kth(root, k):
st, t = [], root
while True:
while t:
st.append(t); t = t.l
t = st.pop(); k -= 1
if k == 0: return t.v
t = t.r
r = build([5, 3, 6, 2, 4, None, None, 1])
print(kth(r, 3), kth(r, 6))What is printed?- A. 3 6
- B. 4 6
- C. 3 5
- D. 2 6
Correct answer: A. 3 6
Iterative in-order traversal visits BST keys in sorted order: 1, 2, 3, 4, 5, 6. The 3rd is 3, the 6th is 6. Stops early, so O(h + k).
More Coding Interview Problems questions
- Problem: Return the diameter of a tree – the number of edges on the longest path between any two nodes. Trees are built by build(xs): a…
- Problem: Find the maximum sum of any path in a tree (a path goes between any two nodes, need not pass through the root, values may be…
- Problem: Count root-to-leaf paths whose values sum to a target. Trees are built by build(xs): a level-order list where index i has…
- Problem: Count downward paths (starting anywhere, ending anywhere below) that sum to k, using prefix sums on the root-to-node path. Trees…
- Problem: Serialize a tree in preorder with '#' for missing children, then count the nodes from the string alone. python class T: def…
- Problem: Rebuild a tree from its preorder and inorder sequences (distinct values) and print its postorder. python def post(pre, ino): if…