Data Structures & AlgorithmsVery hardProduct company OA

What is the maximum path sum in this binary tree, where a path joins any two nodes along parent–child links and need not pass through the root? Tree (parent: left, right): −10: 9, 20; 20: 15, 7; 9: −4, 6; 15: −2, –.

  1. A. 42
  2. B. 40
  3. C. 35
  4. D. 57

Correct answer: A. 42

For each node compute gain = value + the better non-negative child gain, and try value + both child gains as a path peak. At 20: 15 + 20 + 7 = 42. Through the root: 15 + 20 − 10 + (9 + 6) = 40, which is worse because −10 costs more than it connects. '57' adds every positive node, which is not a single path.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic