
地址:
leetcode-cn.com/problems/bi…
/*
思路:
有4种情况要考虑
left + root
right + root
root
left + right + root
不断往上传递的值 只可能是 1, 2, 3中的一种
第四种情况只可能保存在 max里面 而不可能在 curr_max
*/
public class Num124二叉树中的最大路径和 {
private int maxSum = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
helper(root);
return maxSum;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int left = helper(root.left);
int right = helper(root.right);
//单路径最大值,可以参与递归
int curMaxSum = Math.max(root.val, Math.max(left, right) + root.val);
//root+left+right就不能参与递归了,因为已经是一条路径了不能向上再连接root结点了
maxSum = Math.max(maxSum, Math.max(curMaxSum, root.val + left + right));
return curMaxSum;
}
}