Data Structures & AlgorithmsHardProduct company OA

Problem: A node is 'good' if no node on the path from the root to it has a greater value. Count good nodes. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.

Problem: A node is 'good' if no node on the path from the root to it has a greater value. Count good nodes. Trees are built from a level-order list by build(xs) (None = missing child), shown in the code.
from collections import deque
class T:
    def __init__(s, v): s.v, s.l, s.r = v, None, None
def build(xs):  # level order, None = missing child
    root = T(xs[0]); q = deque([root]); i = 1
    while i < len(xs):
        node = q.popleft()
        for side in ("l", "r"):
            if i < len(xs) and xs[i] is not None:
                setattr(node, side, T(xs[i])); q.append(getattr(node, side))
            i += 1
    return root
def good(t, mx=float("-inf")):
    if not t: return 0
    return (t.v >= mx) + good(t.l, max(mx, t.v)) + good(t.r, max(mx, t.v))
print(good(build([4, 2, 6, 5, 1, 4, 8, None, None, 7])))
What is printed?
  1. A. 3
  2. B. 5
  3. C. 4
  4. D. 6

Correct answer: B. 5

Pass the path maximum down. Tree: 4 → (2, 6); 2 → (5, 1); 6 → (4, 8); 1 → (7, –). Good: 4, 6, 5 (path max 4), 8, 7 (path 4, 2, 1, 7). Not good: 2, 1 and the lower 4 (below 6). Equal values count as good (≥). O(n).

More Coding Interview Problems questions

Exams that ask this topic