124.Binary Tree Maximum Path Sum (H)
Last updated
Last updated
public int maxSum=Integer.MIN_VALUE;
public int maxPathSum(TreeNode root){
helper(root);
return maxSum;
}
public int helper(TreeNode root){
if(root==null){
return 0;
}
int left=helper(root.left);
int right=helper(root.right);
//连接父节点的最大路径是一、二、四这三种情况的最大值
int currentSum= Math.max(Math.max(left,right)+root.val,root.val);
//当前节点的最大路径是一、二、三、四这四种情况的最大值
int currentMax= Math.max(currentSum,left+right+root.val);
//用当前最大来更新全局最大
maxSum=Math.max(maxSum,currentMax);
return currentSum;
}class Solution {
int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) {
return 0;
}
// 计算单边路径和时顺便计算最大路径和
oneSideMax(root);
return res;
}
// 定义:计算从根节点 root 为起点的最大单边路径和
int oneSideMax(TreeNode root) {
if (root == null) {
return 0;
}
int leftMaxSum = Math.max(0, oneSideMax(root.left));
int rightMaxSum = Math.max(0, oneSideMax(root.right));
// 后序遍历位置,顺便更新最大路径和
int pathMaxSum = root.val + leftMaxSum + rightMaxSum;
res = Math.max(res, pathMaxSum);
// 实现函数定义,左右子树的最大单边路径和加上根节点的值
// 就是从根节点 root 为起点的最大单边路径和
return Math.max(leftMaxSum, rightMaxSum) + root.val;
}
}