A path goes from one node to another through parent-child links, without visiting a node twice, and it does not need to pass through the root. Find the largest sum of values on any path. Values can be negative.
What to build
A program that finds the maximum path sum in a binary tree given in level order.
Requirements
- A path has at least one node.
- Print the largest sum of the values along any path.
Input
One line: the level-order list of integers, with null for a missing child. The first entry is not null.
Output
The largest path sum.
Constraints
1 ≤ entries ≤ 1000; values between -1000 and 1000.
Example
Input:
1 2 3
Output:
6
Why it works
Every path has a highest node. The best path through a node adds its value to the best downward gains of its two children, where a negative gain is replaced by 0. The answer is the largest such total over all nodes, and each node is handled once.
Examples
1 2 3
6
-10 9 20 null null 15 7
42
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
For each node, the best path that turns at this node is value + best downward gain of left + best downward gain of right.
Hint 2
A child's gain is max(0, its best downward path): ignore a negative branch.
Hint 3
A node is listed after its parent in level order, so processing the nodes from last to first handles children before parents.
Solution
Show one correct solution (try it yourself first)
values = input().split()
val = [int(values[0])]
left = [-1]
right = [-1]
queue = [0]
head = 0
i = 1
while head < len(queue) and i < len(values):
node = queue[head]
head += 1
for side in (left, right):
if i < len(values) and values[i] != "null":
val.append(int(values[i]))
left.append(-1)
right.append(-1)
side[node] = len(val) - 1
queue.append(len(val) - 1)
i += 1
down = [0] * len(val)
best = val[0]
for node in range(len(val) - 1, -1, -1):
lg = max(0, down[left[node]]) if left[node] != -1 else 0
rg = max(0, down[right[node]]) if right[node] != -1 else 0
best = max(best, val[node] + lg + rg)
down[node] = val[node] + max(lg, rg)
print(best)
▶ Open this solution in the compiler, then press Visualize to watch it run step by step