Given a binary tree, determine its maximum path sum. A path is any sequence of nodes connected by edges, with each node appearing at most once.
The path does not have to pass through the root. Return the maximum sum of node values along such a path.
Function Signature
def max_path_sum(tree: list[int | None]) -> int:
Rules
-
The tree is given as a level-order list.
tree[0]
is the root. After that, each node that exists contributes two entries in turn, its left child and then its right child, with
None
for a missing child. Nodes are read level by level, left to right, and trailing
None
entries may be omitted. For example,
[1, None, 2, 3]
is a root 1 whose right child is 2, and 3 is the left child of 2.
-
Each pair of neighboring nodes on a path is joined by a parent-child edge, and no node appears twice. A path may start and end at any nodes.
-
A path contains at least one node, and a single node counts as a path.
Constraints
-
1 <= number of nodes <= 10^4
-
-10^4 <= node value <= 10^4
Examples
Input: tree = [5, 3, 4]
Output: 12
The root 5 has children 3 and 4. The path 3 -> 5 -> 4 uses all three nodes and sums to 12.
Input: tree = [-5, 8, 12, None, None, 10, 6]
Output: 28
The root -5 has children 8 and 12, and 12 has children 10 and 6. The path 10 -> 12 -> 6 sums to 28, while stretching it through the root to 8 gives only 25.
Input: tree = [-2, -1]
Output: -1
The root -2 has a left child -1. Both paths that include -2 sum to less than -1, and the path cannot be empty, so the best choice is the single node -1.