Given a non-empty binary tree, find the maximum path sum.
For this problem****, a path is defined as any node sequence from some starting node to any node in the tree along the parent-child connections.**** The path must contain at least one node and does not need to go through the root.
也就是说 不一定是路径 可以是任何一条路,而root可以是其中的任何一个中间点。
just assume any node can be the inner node of the final results.
but my idea is totally wrong. I don’t even know what I’m doing.
class Solution {
private int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) return 0;
maxPass(root);
return Math.max(maxPathSum(root.left), maxPathSum(root.right));
}
private int maxPass(TreeNode root) {
if (root == null) return 0;
max = Math.max(max, root.val + maxPass(root.left) + maxPass(root.right));
return root.val + maxPass(root.left) + maxPass(root.right);
}
}
but the correct solution is as follows, but it’s so hard to understand.
however, I find some good explainations:
Each node actually has two roles when it comes to function maxPathDown. When processing the final result maxValue, the node is treated as the highest point of a path. When calculating its return value, it is only part of a path (left or right part), and this return value will be used to calculate path sum of other paths with some other nodes(above the current one) as their highest point.
class Solution {
private int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if(root == null) return 0;
helper(root);
return res;
}
private int helper(TreeNode root){ //
if(root == null) return 0;
int left = Math.max(0, helper(root.left)); //如果左边要是小于0 那还不如根本不走left
int right = Math.max(0, helper(root.right)); //同理
res = Math.max(res, left + right + root.val); //root作为路径最高点
return Math.max(left, right) + root.val; //往下走必须选择左或者右的最高点。
}
}