package main import "fmt" type TreeNode struct { Val int Left *TreeNode Right *TreeNode } var maxSum int func maxPathSum(root *TreeNode) int { maxSum = -1 << 31 maxGain(root) return maxSum } func maxGain(node *TreeNode) int { if node == nil { return 0 } leftGain := max(maxGain(node.Left), 0) rightGain := max(maxGain(node.Right), 0) priceNewPath := node.Val + leftGain + rightGain if priceNewPath > maxSum { maxSum = priceNewPath } return node.Val + max(leftGain, rightGain) } func max(a, b int) int { if a > b { return a } return b } func main() { root := &TreeNode{Val: -10} root.Left = &TreeNode{Val: 9} root.Right = &TreeNode{Val: 20} root.Right.Left = &TreeNode{Val: 15} root.Right.Right = &TreeNode{Val: 7} fmt.Println(maxPathSum(root)) }
The maximum path sum is 42, coming from the path 15 -> 20 -> 7 plus the root's right subtree. The path includes nodes with values 15, 20, and 7, summing to 42.
The maximum path sum is the largest sum of values from any path between any two nodes in the tree. The path can start and end anywhere and does not have to pass through the root.
package main import "fmt" type TreeNode struct { Val int Left *TreeNode Right *TreeNode } var maxSum int func maxPathSum(root *TreeNode) int { maxSum = 0 maxGain(root) return maxSum } func maxGain(node *TreeNode) int { if node == nil { return 0 } leftGain := max(maxGain(node.Left), 0) rightGain := max(maxGain(node.Right), 0) priceNewPath := node.Val + leftGain + rightGain if priceNewPath > maxSum { maxSum = priceNewPath } return node.Val + max(leftGain, rightGain) } func max(a, b int) int { if a > b { return a } return b } func main() { root := &TreeNode{Val: -3} fmt.Println(maxPathSum(root)) }
The variable maxSum is initialized to 0, so if all node values are negative, maxSum remains 0, which is incorrect. It should be initialized to the smallest integer to handle negative values properly.
package main import "fmt" type TreeNode struct { Val int Left *TreeNode Right *TreeNode } var maxSum int func maxPathSum(root *TreeNode) int { maxSum = -1 << 31 maxGain(root) return maxSum } func maxGain(node *TreeNode) int { if node == nil { return 0 } leftGain := max(maxGain(node.Left), 0) rightGain := max(maxGain(node.Right), 0) priceNewPath := node.Val + leftGain + rightGain if priceNewPath > maxSum { maxSum = priceNewPath } return node.Val + max(leftGain, rightGain) } func max(a, b int) int { if a > b { return a } return b } func main() { root := &TreeNode{Val: 1} root.Left = &TreeNode{Val: 2} root.Right = &TreeNode{Val: 3} fmt.Println(maxPathSum(root)) }
The code is syntactically correct and compiles successfully. The bit shift operator is valid for initializing maxSum to a very small integer.
Tree structure:
-2
/ \
-1 3
/ \
4 -5
/
2The maximum path sum is 9, coming from the path 2 -> 4 -> 3. Negative nodes are avoided to maximize the sum.