You are given the root of a binary tree where each node contains an integer value (which may be positive, zero, or negative).
A path in the tree is defined as any sequence of nodes such that:
The path sum is the sum of the node values along that path.
Implement a function that returns the maximum path sum over all possible paths in the tree.
You can assume a typical binary tree node definition, for example in a C++/Java-like style:
class TreeNode {
int val;
TreeNode left;
TreeNode right;
}
Write a function:
int maxPathSum(TreeNode root)
which returns the maximum path sum.
Example 1
Input tree (level-order representation): [1, 2, 3]
This corresponds to the structure:
1
/ \
2 3
All possible simple paths and their sums:
Output: 6
Example 2
Input tree (level-order): [-10, 9, 20, null, null, 15, 7]
Structure:
-10
/ \
9 20
/ \
15 7
The maximum path is 15 → 20 → 7 with sum 15 + 20 + 7 = 42.
Output: 42
Example 3
Input tree (single node): [-3]
Only one possible path: the single node itself.
Output: -3