Data Structures & AlgorithmsHardGoogle · Flipkart interview

Problem: Return the maximum path sum between ANY two nodes of a binary tree (a path need not pass through the root; values can be negative).

Problem: Return the maximum path sum between ANY two nodes of a binary tree (a path need not pass through the root; values can be negative).
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]
best = float('-inf')
def gain(nd):
    global best
    if not nd: return 0
    l = max(gain(nd.l), 0); r = max(gain(nd.r), 0)
    best = max(best, nd.v + l + r)
    return nd.v + max(l, r)
gain(build([2, -1, -3, 4, None, -2, 6]))
print(best)
What is printed?
  1. A. 8
  2. B. 5
  3. C. 12
  4. D. 6

Correct answer: A. 8

Left branch gain −1 + 4 = 3; right branch gain −3 + 6 = 3 (the −2 child is clipped to 0). Through the root 2 + 3 + 3 = 8, i.e. the path 4 → −1 → 2 → −3 → 6. A root-to-leaf maximum gives 5, the single best node gives 6, and adding all positive values while ignoring connectivity gives 12.

More Coding Interview Problems questions

Exams that ask this topic