2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_124.java 1.16 KB
一键复制 编辑 原始数据 按行查看 历史
CG国斌 提交于 2021-01-14 15:01 . 二叉树
package com.hit.basmath.interview.top_interview_questions.hard_collection.trees_and_graphs;
import com.hit.common.TreeNode;
/**
* 124. 二叉树中的最大路径和
* <p>
* 给定一个非空二叉树,返回其最大路径和。
* <p>
* 本题中,路径被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。
* <p>
* 示例 1:
* <p>
* 输入:[1,2,3]
* <p>
* 1
* / \
* 2 3
* <p>
* 输出:6
* <p>
* 示例 2:
* <p>
* 输入:[-10,9,20,null,null,15,7]
* <p>
*   -10
*    / \
*   9  20
*     /  \
*    15   7
* <p>
* 输出:42
*/
public class _124 {
private int maxValue = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
maxPathDown(root);
return maxValue;
}
private int maxPathDown(TreeNode node) {
if (node == null) return 0;
int left = Math.max(0, maxPathDown(node.left));
int right = Math.max(0, maxPathDown(node.right));
maxValue = Math.max(maxValue, left + right + node.val);
return Math.max(left, right) + node.val;
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助