package com.heu.wsq.leetcode.tree;
/**
* 124. 二叉树中的最大路径和
* @author wsq
* @date 2021/3/22
* 路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
* 路径和 是路径中各节点值的总和。
* 给你一个二叉树的根节点 root ,返回其 最大路径和 。
*
*
* * 链接:https://leetcode-cn.com/problems/binary-tree-maximum-path-sum
*/
public class MaxPathSum {
private int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
maxPath(root);
return max;
}
private int maxPath(TreeNode root){
if(root == null){
return 0;
}
int pathSum = root.val;
// 递归计算左右子节点的最大贡献值
// 只有在最大贡献值大于 0 时,才会选取对应子节点
int leftGain = Math.max(maxPath(root.left), 0);
int rightGain = Math.max(maxPath(root.right), 0);
int tmpMax = pathSum + leftGain + rightGain;
max = Math.max(max, tmpMax);
// 返回父节点时,只能返回当前子树root与左节点或者右节点或者根节点自己构成的路径
return pathSum + Math.max(leftGain, rightGain) ;
}
}
124. 二叉树中的最大路径和(二叉树路径问题)
最新推荐文章于 2025-09-01 18:18:00 发布
这篇博客主要介绍了如何解决LeetCode上的第124题——二叉树中的最大路径和。作者通过Java代码详细解释了如何递归计算每个节点的最大路径贡献,并在遍历过程中更新全局的最大路径和。算法的关键在于只保留对当前路径和有正贡献的子节点,以找到最大的路径。
563

被折叠的 条评论
为什么被折叠?



