Files
LeetCode-Go/leetcode/0124.Binary-Tree-Maximum-Path-Sum/124. Binary Tree Maximum Path Sum.go
2020-08-07 17:06:53 +08:00

48 lines
799 B
Go

package leetcode
import "math"
import (
"github.com/halfrost/LeetCode-Go/structures"
)
// TreeNode define
type TreeNode = structures.TreeNode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func maxPathSum(root *TreeNode) int {
if root == nil {
return 0
}
max := math.MinInt32
getPathSum(root, &max)
return max
}
func getPathSum(root *TreeNode, maxSum *int) int {
if root == nil {
return math.MinInt32
}
left := getPathSum(root.Left, maxSum)
right := getPathSum(root.Right, maxSum)
currMax := max(max(left+root.Val, right+root.Val), root.Val)
*maxSum = max(*maxSum, max(currMax, left+right+root.Val))
return currMax
}
func max(a int, b int) int {
if a > b {
return a
}
return b
}