124. Binary Tree Maximum Path Sum #
Problem #
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
Problem Summary #
Given a non-empty binary tree, return its maximum path sum. In this problem, a path is defined as a sequence starting from any node in the tree and reaching any node. The path must contain at least one node and does not necessarily have to pass through the root node.
Solution Approach #
- Given a binary tree, find a path such that the sum of the path is the largest.
- The idea for this problem is relatively simple: recursively maintain the maximum value. However, there are many objects that need to be compared.
maxPathSum(root) = max(maxPathSum(root.Left), maxPathSum(root.Right), maxPathSumFrom(root.Left) (if>0) + maxPathSumFrom(root.Right) (if>0) + root.Val), wheremaxPathSumFrom(root) = max(maxPathSumFrom(root.Left), maxPathSumFrom(root.Right)) + root.Val
Code #
package leetcode
import "math"
/**
* 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
}