Leetcode - Word Pattern
Leetcode - Longest Univalue Path

Leetcode - Binary Tree Maximum Path Sum

violet posted @ Apr 30, 2020 04:43:02 AM in 算法 with tags Algorithm Golang tree , 177 阅读

https://leetcode.com/problems/binary-tree-maximum-path-sum/

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

 

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func maxPathSum(root *TreeNode) int {
    maxNum := math.MinInt32
    count(root, &maxNum)
    
    return maxNum
}

func count(root *TreeNode, maxNum *int) int {
    if root == nil {
        return 0
    }
    left := max(0, count(root.Left, maxNum))
    right := max(0, count(root.Right, maxNum))
    *maxNum = max(*maxNum, left + right + root.Val)
    
    return max(left, right) + root.Val
}

func max(a, b int) int {
    if a > b {
        return a
    }
    
    return b
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter