[路飞]_每天刷leetcode_38(二叉树中的最大路径和 Binary Tree Maximum Path Sum)

154 阅读2分钟

二叉树中的最大路径和(Binary Tree Maximum Path Sum)

LeetCode传送门124. Binary Tree Maximum Path Sum

题目

路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。

路径和 是路径中各节点值的总和。

给你一个二叉树的根节点 root ,返回其 最大路径和 。

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node's values in the path.

Given the root of a binary tree, return the maximum path sum of any non-empty path.

Example:

Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.

Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.

Constraints:

  • The number of nodes in the tree is in the range [1,3104][1, 3 * 10^4].
  • -1000 <= Node.val <= 1000

思考线


解题思路

解题是参考了官方解答

首先我们可以计算一下二叉树种从某个节点开始最大的贡献值(就是在以该节点为根节点的子树中寻找以该节点为起点的一条路径,使得该路径上的节点值之和最大。)

如此我们可以写一个递归函数maxGain(node)

  • 终止条件为 node === null, 此时最大贡献值为0;
  • 非空节点的最大贡献值等于节点值与其子节点中的最大贡献值之和。

根据函数 maxGain 得到每个节点的最大贡献值之后,如何得到二叉树的最大路径和?对于二叉树中的一个节点,该节点的最大路径和取决于该节点的值与该节点的左右子节点的最大贡献值,如果子节点的最大贡献值为正,则计入该节点的最大路径和,否则不计入该节点的最大路径和。维护一个全局变量 maxSum 存储最大路径和,在递归过程中更新 maxSum 的值,最后得到的 maxSum 的值即为二叉树中的最大路径和。

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function maxPathSum(root: TreeNode | null): number {
    const max_sum= {
        value: Number.MIN_SAFE_INTEGER
    }
    maxGain(root, max_sum);
    return max_sum.value;
};
type Global_number = {
    value: number;
}
function maxGain(root: TreeNode | null, max_sum: Global_number): number {
    if (!root) return 0;
    const left = Math.max(maxGain(root.left, max_sum), 0);
    const right = Math.max(maxGain(root.right, max_sum), 0);
    if (max_sum.value < (root.val + left + right)) {
        max_sum.value = root.val + left + right;
    }
    return root.val + Math.max(left, right);
}

这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。