https://leetcode.com/problems/binary-tree-maximum-path-sum/
这道题可以用递归做,首先,应该有一个全局变量来保存当前遇到的最大path值。
对于每个节点而言,经过它的最大path值,应该是左边的最大path加右边的最大path加自己,如果左边或者右边的最大path是负数,那么就不加这一部分。
另外,对于这个节点的父节点而言,经过父节点的path不可能同时经过这个节点的左右子树,只能经过这个节点的左子树或者右子树,因此这个节点返回给它的父节点的,应该是它单边的最大path
public class Solution {
public int maxPathSum(TreeNode root) {
int[] max = new int[1];
max[0] = root.val;
getMax(root, max);
return max[0];
}
public int getMax(TreeNode root, int[] max){
if(root==null) return 0;
int left = getMax(root.left, max);
int right = getMax(root.right, max);
if(left<0) left=0;
if(right<0) right = 0;
int localMax = root.val+left+right;
if(localMax>max[0]) max[0] = localMax;
return Math.max(root.val+left, root.val+right);
}
}