mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
48 lines
799 B
Go
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
|
|
}
|