Skip to content

Commit 7f35cfa

Browse files
committed
add: MaximumPathSum
1 parent 15217bf commit 7f35cfa

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

java/Trees/MaximumPathSum.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import DS.TreeNode;
2+
3+
/*
4+
// Definition of TreeNode:
5+
class TreeNode {
6+
public int val;
7+
public TreeNode left;
8+
public TreeNode right;
9+
public TreeNode(int val) {
10+
this.val = val;
11+
}
12+
}
13+
*/
14+
15+
public class MaximumPathSum {
16+
int maxSum = Integer.MIN_VALUE;
17+
18+
public int maxPathSum(TreeNode root) {
19+
maxPathSumHelper(root);
20+
return maxSum;
21+
}
22+
23+
private int maxPathSumHelper(TreeNode node) {
24+
// Base case: null nodes have no path sum.
25+
if (node == null) {
26+
return 0;
27+
}
28+
// Collect the maximum gain we can attain from the left and right
29+
// subtrees, setting them to 0 if they're negative.
30+
int leftSum = Math.max(maxPathSumHelper(node.left), 0);
31+
int rightSum = Math.max(maxPathSumHelper(node.right), 0);
32+
// Update the overall maximum path sum if the current path sum is
33+
// larger.
34+
maxSum = Math.max(maxSum, node.val + leftSum + rightSum);
35+
// Return the maximum sum of a single, continuous path with the
36+
// current node as an endpoint.
37+
return node.val + Math.max(leftSum, rightSum);
38+
}
39+
}

0 commit comments

Comments
 (0)