Loading

[LeetCode] 124. Binary Tree Maximum Path Sum(二叉树的最大路径和)

Description

Given a non-empty binary tree, find the maximum path sum.
给定一非空二叉树,找到其最大路径和。

For this problem, a path is defined as any node sequence 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.
对于这个问题,『路径』被定义为树中任意一节点,经由父子节点间的连接,经过若干节点,到达树中另外一节点的节点序列。该序列需至少包含一个节点,且并不要求一定要经过树根。

Examples

Example 1

Input: root = [1,2,3]
Output: 6

Example 2

Input: root = [-10,9,20,null,null,15,7]
Output: 42

Constraints

  • The number of nodes in the tree is in the range [0, 3e4].
  • -1000 <= Node.val <= 1000

Solution

一遇到二叉树的题目,递归解题通常是首先考虑的。在本题中,最大盒的路径可能有以下几种情况:

  1. 完全位于左子树;

  2. 完全位于右子树;

  3. 跨越 root

于是可以写出以下代码:

/**
 * Example:
 * var ti = TreeNode(5)
 * var v = ti.`val`
 * Definition for a binary tree node.
 * class TreeNode(var `val`: Int) {
 *     var left: TreeNode? = null
 *     var right: TreeNode? = null
 * }
 */
import kotlin.math.max

class Solution {
    private var result = Int.MIN_VALUE

    fun maxPathSum(root: TreeNode?): Int {
        result = Int.MIN_VALUE
        dfs(root)
        return result
    }

    private fun dfs(root: TreeNode?): Int {
        if (root == null) {
            return 0
        }
        val leftVal = max(dfs(root.left), 0)
        val rightVal = max(dfs(root.right), 0)

        result = max(result, leftVal + root.`val` + rightVal)
        return max(leftVal, rightVal) + root.`val`
    }
}

上述代码里要注意的地方有二:一是递归函数的返回值,返回的是左/右子树和的最大值。二是如果遇到左右子树和为负数的情况时,要舍去。

posted @ 2020-12-25 10:48  Zhongju.copy()  阅读(67)  评论(0编辑  收藏  举报