call(back)
Algorithms & Data StructureshardSign in to star problems

Binary Tree Maximum Path Sum, With the Path

A binary tree has n nodes numbered 0 to n - 1, with the root at node 0. Node i has value values[i] (possibly negative), left child left[i] and right child right[i], where -1 means no child.

A path is a sequence of distinct nodes in which each consecutive pair is joined by a parent-child edge. It may start and end anywhere and does not have to pass through the root, but it must contain at least one node. Return a path with the largest possible sum of values, as the list of node indices in order from one end to the other.

values = [-10, 9, 20, 15, 7]
left   = [  1, -1,  3, -1, -1]
right  = [  2, -1,  4, -1, -1]
answer = [3, 2, 4]          // 15 + 20 + 7 = 42; [4, 2, 3] is equally good

If several paths tie, return any of them: the grader checks that your list is a real path and compares its sum with the optimum. Up to 10,000 nodes.

Hints

Hint 1

First solve for the sum. For each node compute down[v], the best sum of a path that starts at v and goes only downward; a negative arm is dropped.

Hint 2

The best path that bends at v is values[v] plus the positive left arm plus the positive right arm.

Hint 3

To recover the nodes, remember for each node which child its best downward arm continues into. The answer is the left arm reversed, the bend node, then the right arm.

Topics

Asked at

Similar Problems6