Thought:
Use a class variable to keep track of the maximum path ever seen( either across the root of not).
Use another method to calculate the maximum path ends with some specific node.
Then get the result.
public class Solution {
public static int maxAcrossRoot = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
maxAcrossRoot = Integer.MIN_VALUE;
int result = maxEndsRoot(root);
return Math.max(result, maxAcrossRoot);
}
public int maxEndsRoot(TreeNode root) {
if(root == null) return 0;
int left = maxEndsRoot(root.left);
int right = maxEndsRoot(root.right);
int temp = root.val;
if(left > 0) temp += left;
if(right > 0) temp += right;
maxAcrossRoot = Math.max(temp, maxAcrossRoot);
return Math.max(root.val, Math.max(root.val + left, root.val + right));
}
}
No comments:
Post a Comment