

java
/**
* 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 maxSum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
calculateSinglePath(root);
return maxSum;
}
//计算当前节点能为父节点提供的最大路径和
private int calculateSinglePath(TreeNode node){
if(node == null){
return 0;
}
//递归计算左右子树
int leftProfit = Math.max(0,calculateSinglePath(node.left));
int rightProfit = Math.max(0,calculateSinglePath(node.right));
//倒V型的内部和
int currentInternalSum = leftProfit + node.val + rightProfit;
maxSum = Math.max(maxSum, currentInternalSum);
return node.val + Math.max(leftProfit,rightProfit);
}
}
maxSum用于记录全局最终的最大值;而函数返回值用于记录局部最大值,往上传递给父节点