Best path in a tree
A tree is written as nested tuples, (value, left, right), with None for a missing child. Values may be negative.
A path is a connected chain of nodes, each used at most once. It need not pass through the root, but it cannot branch. Find the largest possible sum of a path with at least one node.
leaf = lambda v: (v, None, None)
best_path((1, leaf(2), leaf(3))) # 6Two different questions
At each node, you need to work out two things:
- The best sum of a path bending here, which may use both children. That is a candidate for the overall answer.
- The best sum going down one side only. That is all a parent can extend.
Children that would reduce the total should be left out, so treat a negative downward sum as 0. Track the overall best in a variable shared across calls with nonlocal.
Your task
Write best_path(tree) returning the largest sum of any path in a non-empty tree given as nested (value, left, right) tuples.
The explanation opens here once every check passes.