Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Problem: Insert keys into an empty BST in the given order, then report the lowest common ancestor of three pairs.
Problem: Insert keys into an empty BST in the given order, then report the lowest common ancestor of three pairs.
class T:
def __init__(s, v): s.v, s.l, s.r = v, None, None
def ins(r, v):
if not r: return T(v)
if v < r.v: r.l = ins(r.l, v)
else: r.r = ins(r.r, v)
return r
def lca(r, a, b):
while r:
if a < r.v and b < r.v: r = r.l
elif a > r.v and b > r.v: r = r.r
else: return r.v
root = None
for v in [20, 8, 22, 4, 12, 10, 14]: root = ins(root, v)
print(lca(root, 10, 22), lca(root, 10, 14), lca(root, 4, 14))What is printed?- A. 20 10 8
- B. 8 12 8
- C. 20 12 4
- D. 20 12 8
Correct answer: D. 20 12 8
In a BST the LCA is the first node whose value lies between the two keys (inclusive). 10 and 22 split at the root 20; 10 and 14 split at 12; 4 and 14 split at 8.
More Coding Interview Problems questions
- Problem: A node is 'good' if no node on the path from the root to it has a greater value. Trees are built from a level-order list with…
- Problem: Return the maximum path sum between ANY two nodes of a binary tree (a path need not pass through the root; values can be…
- Problem: Count islands in a grid of 1s (land) and 0s where land cells touching even DIAGONALLY belong to the same island. python g =…
- Problem: In an unweighted graph, find the shortest distance from node 0 to node 5 and the NUMBER of distinct shortest paths. python from…
- A Floyd–Warshall implementation writes its loops as for i … for j … for k (k innermost) instead of k outermost, and runs the triple loop…
- Problem: Build a minimum spanning tree with Kruskal's algorithm and report its total weight. python edges =…