Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE
Problem: Find the lowest common ancestor of two keys 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 lowest common ancestor of two keys 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 lca(t, p, q):
while t:
if p < t.v and q < t.v: t = t.l
elif p > t.v and q > t.v: t = t.r
else: return t.v
r = build([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5])
print(lca(r, 2, 8), lca(r, 3, 5), lca(r, 2, 4))What is printed?- A. 6 4 4
- B. 6 4 2
- C. 6 2 2
- D. 2 4 2
Correct answer: B. 6 4 2
Walk down while both keys are on the same side; the first node that splits them (or equals one of them) is the LCA. 2 and 8 split at 6; 3 and 5 split at 4; for 2 and 4, node 2 is itself an ancestor of 4. O(h).
More Coding Interview Problems questions
- 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…
- 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…