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?
  1. A. 5
  2. B. 3
  3. C. 6
  4. 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

Exams that ask this topic