algorighm/top-interview-leetcode150/binary-tree/124二叉树中最大路径和.js

65 lines
2.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
* https://leetcode.cn/problems/binary-tree-maximum-path-sum/?envType=study-plan-v2&envId=top-interview-150
*/
const maxPathSum = function (root) {
};
/**
* 计算二叉树中的最大路径和。路径和的定义是:
* 从任意节点出发,沿着父子节点的路径进行移动,且路径和的值为路径上所有节点的值之和。
* 一个路径的最大和可能穿过根节点,也可能不穿过根节点。
*
* 1. 初始化变量 `maxSum` 为负无穷,表示初始时的最大路径和。
* 2. 使用一个递归函数 `maxGain(node)`,计算以当前节点为起点的路径和贡献值。
* - 如果当前节点为空,返回 0没有路径贡献
* - 对于每个节点,我们分别计算其左子树和右子树的最大贡献值。
* - `leftGain` 和 `rightGain` 代表左右子树的最大路径贡献,若为负数,则选择为 0避免影响结果。
* - 计算该节点的最大路径和 `priceNewPath`,这是通过当前节点的值加上左右子树的最大贡献值得到的。
* - 更新 `maxSum` 为当前路径和与已知最大路径和的较大者。
* - 返回该节点的最大贡献值,它等于当前节点的值加上左右子树贡献中的较大者。
*
* 3. 在 `maxPathSum` 中,调用 `maxGain(root)` 来递归计算最大路径和。
* 4. 最终,`maxSum` 将包含二叉树中的最大路径和,返回这个值作为结果。
*
* 需要注意:
* - 每个节点的最大贡献值是考虑到该节点本身以及它的左右子节点的最大贡献。
* - 我们只选择左右子树中贡献值大于零的部分,因为负值的路径会减少总和。
* - `maxSum` 记录的是整个树中的最大路径和,它可能并不经过根节点。
*/
function f1(root) {
let maxSum = -Infinity; // 初始化为最小的整数
// 内部的递归函数,返回以当前节点为起点的最大路径贡献值
function maxGain(node) {
if (!node) return 0;
// 递归计算左右子节点的最大贡献值只有在大于0时才会选择该节点
const leftGain = Math.max(maxGain(node.left), 0);
const rightGain = Math.max(maxGain(node.right), 0);
// 当前节点的最大路径和为该节点值加上左右子树的最大贡献值
const priceNewPath = node.val + leftGain + rightGain;
// 更新答案
maxSum = Math.max(maxSum, priceNewPath);
// 返回该节点的最大贡献值
return node.val + Math.max(leftGain, rightGain);
}
maxGain(root); // 开始递归计算
return maxSum; // 返回结果
}