题目描述
路径 被定义为一条从树中任意节点出发,沿父节点-子节点连接,达到任意节点的序列。同一个节点在一条路径序列中 至多出现一次 。该路径 至少包含一个 节点,且不一定经过根节点。
路径和 是路径中各节点值的总和。
给你一个二叉树的根节点 root ,返回其 最大路径和 。
示例 1:
输入:root = [1,2,3] 输出:6 解释:最优路径是 2 -> 1 -> 3 ,路径和为 2 + 1 + 3 = 6
示例 2:
输入:root = [-10,9,20,null,null,15,7]
输出:42
解释:最优路径是 15 -> 20 -> 7 ,路径和为 15 + 20 + 7 = 42
提示:
树中节点数目范围是 [1, 3 * 10^4]
-1000 <= Node.val <= 1000
1、一个节点的最大贡献值:该节点必须为根节点 且 该节点必须为起点 的一条路径的最大值
左右子树最大贡献值中的较大值且必须大于0,加上节点自身的值
2、该节点的最大路径和:如果左节点的最大贡献值为正,就计入
如果右节点的最大贡献值为正,就计入
加上该节点的值
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int max=Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if(root==null)
return 0;
maxGong(root);
return max;
}
public int maxGong(TreeNode root)
{
if(root==null)
return 0;
int l=Math.max(maxGong(root.left),0);
int r=Math.max(maxGong(root.right),0);
max=Math.max(max,root.val+l+r);
return root.val+Math.max(l,r);
}
}