本题的思路其实和 Longest Univalue Path 这题的内容是一致的, 如果最长相同数值路径的逻辑能明白, 这里就是把数值相等的判断, 换成了数值加和的判断
递归思路
二叉树的路径问题常用递归来解决, 这里递归函数求的是以当前结点为起始的链路的最大值, 这里可能存在三种情况 :
- 以当前结点为起始的左子树链路为最大值
- 以当前结点为起始的右子树链路为最大值
- 不包含左右子树, 当前结点就是最大值
而我们要求的最大路径和 res 对应的链路是可以左子树 + 当前结点 + 右子树的情况的, 所以我们在这个过程中, 还要对我们的 res 进行数值上的更新.
class Solution {
private int res;
public int maxPathSum(TreeNode root) {
// set the initial value
res = Integer.MIN_VALUE;
PathSum(root);
return res;
}
public int PathSum(TreeNode node) {
if (node == null)
return 0;
// the max path sum start with the left child tree
int left = PathSum(node.left);
// the max path sum start with the right child tree
int right = PathSum(node.right);
if (left >= 0) {
res = Math.max(res, right >= 0 ? left + right + node.val : left + node.val);
} else {
res = Math.max(res, right >= 0 ? right + node.val : node.val);
}
// we have to return the max path sum start with current node
if (left >= 0)
return right >= 0 ? Math.max(left, right) + node.val : left + node.val;
else
return right >= 0 ? right + node.val : node.val;
}
}
上面的代码是我自己完成的, 但是很明显这里的数值运算加上了太多的判断, 这里可以进行优化, 当 left 或者 right 的数值小于 0 的情况下, 我们是肯定不会加上该数值的, 所以可以直接将该数值变为 0, 后面的运算就可以都加上来.
class Solution {
private int res;
public int maxPathSum(TreeNode root) {
// set the initial value
res = Integer.MIN_VALUE;
PathSum(root);
return res;
}
public int PathSum(TreeNode node) {
if (node == null)
return 0;
// the max path sum start with the left child tree
int left = PathSum(node.left);
// the max path sum start with the right child tree
int right = PathSum(node.right);
if (left < 0) left = 0;
if (right < 0) right = 0;
res = Math.max(left + right + node.val, res);
// we have to return the max path sum start with current node
return Math.max(left, right) + node.val;
}
}