124. Binary Tree Maximum Path Sum
Last updated
Last updated
class Solution {
int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
helper(root);
return res;
}
private int helper(TreeNode root) {
if (root == null) return 0;
int left = Math.max(0, helper(root.left)); // key point, abandon negtive
int right = Math.max(0, helper(root.right));
// update max_sum if it's better to start a new path,
// res: origin path result,
// left + right + root.val => new path result
res = Math.max(res, left + right + root.val);
return Math.max(left, right) + root.val; // compare left, right
}
}int left = Math.max(0, helper(root.left)); // key point, abandon negtive
int right = Math.max(0, helper(root.right));
```java
class Solution {
public int maxPathSum(TreeNode root) {
int[] result = new int[]{Integer.MIN_VALUE};
dfs(root, result);
return result[0];
}
private int dfs(TreeNode node, int[] result) {
if (node == null) {
return 0;
}
int left = Math.max(0, dfs(node.left, result));
int right = Math.max(0, dfs(node.right, result));
result[0] = Math.max(result[0], left + right + node.val);
return Math.max(left, right) + node.val;
}
}
```