class Solution {
private int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
getMax(root);
return res;
}
private int getMax(TreeNode root){
if(root == null) return 0;
int left = Math.max(0,getMax(root.left));//左递归
int right = Math.max(0,getMax(root.right)); //右递归
res = Math.max(res,root.val+left+right);//每轮更新res
return Math.max(left,right) + root.val;//每轮返回左右子树中的最大值与每轮的根节点相加
}
}
0ms