Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Count subtrees in which every node has the same value.
Problem: Count subtrees in which every node has the same value.
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]
cnt = 0
def uni(n):
global cnt
if not n: return True
l, r = uni(n.l), uni(n.r)
if l and r and (not n.l or n.l.v == n.v) and (not n.r or n.r.v == n.v):
cnt += 1; return True
return False
uni(build([5, 1, 5, 5, 5, None, 5, 1]))
print(cnt)What is printed?- A. 5
- B. 3
- C. 6
- D. 4
Correct answer: D. 4
Tree: 5 → (1, 5); 1 → (5, 5); right 5 → (−, 5); the left-left 5 has child 1. Univalue subtrees: the leaf 1, the leaf 5 under 1, the leaf 5 under the right 5, and the right 5's subtree (5, 5). The subtree rooted at the 5 with child 1 is not univalue, so the count is 4.
More Coding Interview Problems questions
- 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…
- Problem: Find a target's index in a rotated sorted array of distinct values in O(log n). python def search(a, t): lo, hi = 0, len(a) - 1…
- Problem: You take trains in order; train i covers dist[i] km at a common integer speed, and every train except the last departs only at an…
- Problem: Koko eats from one pile per hour at speed k bananas/hour (if a pile has fewer, she finishes it and waits). Find the minimum k to…
- Problem: Length of the longest common subsequence of THREE strings (3-D DP). python def lcs3(a, b, c): dp = [[[0] (len(c) + 1) for in…