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
在二叉树中找出一条路径,该路径和最大。注意:该路径可能没有经过根节点,也可能不包含叶子节点。
先把问题分为两种情况:(1)该路径包含根节点 (2)该路径不包含根节点,该路径处于根节点的左子树或者右子树中。
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
var mm map[*TreeNode]int
func maxPathSum(root *TreeNode) int {
mm = make(map[*TreeNode]int)
initMap(root)
return helper(root)
}
func helper(root *TreeNode) int {
withoutRoot := 0
switch {
case root == nil:
return 0
case isLeaf(root):
return root.Val
case root.Left == nil:
withoutRoot = helper(root.Right)
case root.Right == nil:
withoutRoot = helper(root.Left)
default:
withoutRoot = max(helper(root.Left), helper(root.Right))
}
withRoot := root.Val
if mm[root.Left] > 0 {
withRoot += mm[root.Left]
}
if mm[root.Right] > 0 {
withRoot += mm[root.Right]
}
return max(withRoot, withoutRoot)
}
func initMap(root *TreeNode) (res int) {
switch {
case root == nil:
res = 0
case isLeaf(root):
mm[root] = root.Val
if root.Val < 0 {
res = 0
} else {
res = root.Val
}
default:
mm[root] = max(initMap(root.Left), initMap(root.Right)) + root.Val
res = mm[root]
}
return
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
func isLeaf(root *TreeNode) bool {
return root.Left == nil && root.Right == nil
}