124. Binary Tree Maximum Path Sum
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/
9 20
/
15 7
Output: 42
花花酱
func maxPathSum(root *TreeNode) int {
if root == nil {
return 0
}
res := math.MinInt32
maxPathSumCore(root, &res)
return res
}
func maxPathSumCore(root *TreeNode, ans *int) int {
if root == nil {
return 0
}
l := math.Max(0.0, float64(maxPathSumCore(root.Left, ans)))
r := math.Max(0.0, float64(maxPathSumCore(root.Right, ans)))
*ans = int(math.Max(l + r+float64(root.Val), float64(*ans)))
return int(math.Max(l, r)) + root.Val
}