Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: A node is 'good' if no node on the path from the root to it has a greater value. Trees are built from a level-order list with None for gaps.

Problem: A node is 'good' if no node on the path from the root to it has a greater value. Trees are built from a level-order list with None for gaps.
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 good(nd, mx):
    if not nd: return 0
    g = 1 if nd.v >= mx else 0
    m = max(mx, nd.v)
    return g + good(nd.l, m) + good(nd.r, m)
print(good(build([5, 3, 8, 6, 1, None, 9, None, 7]), float('-inf')))
What is printed?
  1. A. 4
  2. B. 5
  3. C. 6
  4. D. 3

Correct answer: B. 5

Tree: 5 → (3, 8); 3 → (6, 1); 8 → (−, 9); 6 → (−, 7). Good nodes: 5, 8, 6 (path max 5), 9 and 7 (path max 6), i.e. 5. 3 and 1 are below the root value 5.

More Coding Interview Problems questions

Exams that ask this topic