Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Lowest common ancestor in a general binary tree (not a BST), with the recursive 'return whichever side found something' method.
Problem: Lowest common ancestor in a general binary tree (not a BST), with the recursive 'return whichever side found something' method.
class T:
def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):
nodes = [T(x) if x is not None else None for x in xs]
kids = iter(nodes[1:])
for nd in nodes:
if nd:
nd.l = next(kids, None); nd.r = next(kids, None)
return nodes[0]
def lca(nd, p, q):
if not nd or nd.v in (p, q): return nd
l, r = lca(nd.l, p, q), lca(nd.r, p, q)
return nd if l and r else l or r
root = build([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4])
print(lca(root, 7, 8).v, lca(root, 7, 6).v, lca(root, 5, 4).v)What is printed?- A. 5 5 2
- B. 3 2 5
- C. 3 5 5
- D. 1 5 5
Correct answer: C. 3 5 5
7 is under 5 (via 2) and 8 is under 1, so they meet at the root 3. 7 and 6 are both under 5. For 5 and 4, the search returns 5 as soon as it reaches it, because 4 lies inside 5's subtree, so 5 is its own LCA.
More Coding Interview Problems questions
- Problem: Delete the nodes with given values from a binary tree and return the roots of the remaining forest, sorted. python class T: def…
- Problem: Print the boundary of a binary tree anticlockwise: root, left boundary (excluding leaves), all leaves left to right, then the…
- Problem: Convert a BST so each node's value becomes the sum of all values ≥ it (reverse inorder with a running sum); print the new…
- Problem: Count subtrees in which every node has the same value. python class T: def init(s, v): s.v, s.l, s.r = v, None, None def…
- Problem: Rain falls on a 2-D height map. Compute the trapped water volume with a min-heap that grows inward from the border. python import…
- Problem: Remove the fewest DISTINCT values so that at least half of the array's elements are removed (greedy on frequencies). python from…