Binary Tree Maximum Path Sum
Example
Input: [1,2,3]
1
/ \
2 3
Output: 6Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42Note
Code
Last updated
Input: [1,2,3]
1
/ \
2 3
Output: 6Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42Last updated
singlePath: 从root往下走到任意点的最大路径,这条路径可以不包含任何点
maxPath: 从树中任意到任意点的最大路径,这条路径至少包含一个点
如果节点为空:singlePath = 0,maxPath = -infsinglePath = root值加上左右singlePath的更大者 并维护singlePath >= 0
maxPath = 左右maxPath的更大者, 维护maxPath为root值加上左右singlePathpublic class Solution {
private class ResultType {
int singlePath, maxPath;
ResultType(int singlePath, int maxPath) {
this.singlePath = singlePath;
this.maxPath = maxPath;
}
}
private ResultType helper(TreeNode root) {
if (root == null) {
return new ResultType(0, Integer.MIN_VALUE);
}
// Divide
ResultType left = helper(root.left);
ResultType right = helper(root.right);
// Conquer
int singlePath = Math.max(left.singlePath, right.singlePath) + root.val;
singlePath = Math.max(singlePath, 0);
int maxPath = Math.max(left.maxPath, right.maxPath);
maxPath = Math.max(maxPath, left.singlePath + right.singlePath + root.val);
return new ResultType(singlePath, maxPath);
}
public int maxPathSum(TreeNode root) {
ResultType result = helper(root);
return result.maxPath;
}
}class Solution {
int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
if (root == null) {
return 0;
}
int left = helper(root.left);
int right = helper(root.right);
return max(res, root.val,
left + root.val + right,
left + root.val,
right + root.val);
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int left = helper(root.left);
int right = helper(root.right);
if (left < 0) {
res = max(res, root.val, root.val + right);
} else if (right < 0) {
res = max(res, root.val, root.val + left);
} else {
res = Math.max(res, root.val + left + right);
}
return max(root.val, root.val + left, root.val + right);
}
private int max(int a, int b, int c) {
return Math.max(a, Math.max(b, c));
}
private int max(int a, int b, int c, int d, int e) {
return max(max(a, b, c), d, e);
}
}