题目
思路
本题中路径可以从任意节点出发,到达任意节点,不一定只能向下,也不一定要经过根节点
对于一棵树来说,最大的路径要么经过根节点,要么不经过
-
经过根节点:
最大值 = 根节点 + 左边子树往下能延伸的最大值 + 右边子树往下能延伸的最大值
-
不经过根节点:
max(左子树上的最大值,右子树上的最大值)
- 那么左子树上的最大值怎么算呢?同样,也分经不经过左子树上的根节点,依次递归下去
代码
static class Info{
int single;
int max;
public Info(int single, int max) {
this.single = single;
this.max = max;
}
}
public int maxPathSum(TreeNode root) {
Info info = process(root);
return info.max;
}
private Info process(TreeNode root) {
if (root == null) {
return new Info(Integer.MIN_VALUE,Integer.MIN_VALUE);
}
Info left = process(root.left);
Info right = process(root.right);
// 左子树往下延伸的最大值
int leftMax = Math.max(left.single,0);
// 右子树往下延伸的最大值
int rightMax = Math.max(right.single, 0);
// 经过根节点的最大值
int single = Math.max(leftMax,rightMax) + root.val;
int max = Math.max(Math.max(left.max,right.max),root.val + leftMax + rightMax);
return new Info(single,max);
}