package main
import (
"fmt"
"math"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func maxPathSum(root *TreeNode) int {
maxSum := math.MinInt64
var dfs func(node *TreeNode) int
dfs = func(node *TreeNode) int {
if node == nil {
return 0
}
left := max(dfs(node.Left), 0) // ignore negative sums
right := max(dfs(node.Right), 0)
currentSum := node.Val + left + right
if currentSum > maxSum {
maxSum = currentSum // update max if current path is better
}
return node.Val + max(left, right) // return max path sum including one child
}
dfs(root)
return maxSum
}
func main() {
root := &TreeNode{Val: 1}
root.Left = &TreeNode{Val: 2}
root.Right = &TreeNode{Val: 3}
root.Left.Left = &TreeNode{Val: 4}
root.Left.Right = &TreeNode{Val: -5}
root.Right.Right = &TreeNode{Val: 6}
result := maxPathSum(root)
fmt.Println(result)
}
left := max(dfs(node.Left), 0) // ignore negative sums
calculate max path sum from left child, ignore negative sums to avoid reducing total
right := max(dfs(node.Right), 0)
calculate max path sum from right child, ignore negative sums
currentSum := node.Val + left + right
sum path through current node including both children
if currentSum > maxSum {
maxSum = currentSum // update max if current path is better
}
update global max path sum if current path is larger
return node.Val + max(left, right) // return max path sum including one child
return max sum path continuing upwards through one child