Skip to content

Commit 56e3cab

Browse files
Implement Maximum Path Sum in a binary tree
1 parent 0f90e3d commit 56e3cab

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
14+
* }
15+
*/
16+
class MaximumPathSum {
17+
int maxSum = Integer.MIN_VALUE;
18+
public int maxPathSum(TreeNode root) {
19+
postorder(root);
20+
return maxSum;
21+
}
22+
23+
int postorder(TreeNode node){
24+
if(node == null){
25+
return 0;
26+
}
27+
28+
int left = postorder(node.left);
29+
int right = postorder(node.right);
30+
maxSum = Math.max(maxSum, node.val+Math.max(0,left)+Math.max(0,right));
31+
return node.val+Math.max(Math.max(0,left), Math.max(0,right));
32+
}
33+
}

0 commit comments

Comments
 (0)