forked from sambit77/Algoexpert-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxPathSumLeetCodeWay.java
More file actions
44 lines (37 loc) · 1.3 KB
/
MaxPathSumLeetCodeWay.java
File metadata and controls
44 lines (37 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//Problem Link:- https://leetcode.com/problems/binary-tree-maximum-path-sum/
//All test cases passed in LeetCode
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private int globalMaximumSum;
public int maxPathSum(TreeNode root) {
globalMaximumSum = Integer.MIN_VALUE;
findMaxPathSum(root);
return globalMaximumSum;
}
private int findMaxPathSum(TreeNode currentNode) {
if (currentNode == null) {
return 0;
}
int maxPathSumLeft = findMaxPathSum(currentNode.left);
int maxPathSumRight = findMaxPathSum(currentNode.right);
maxPathSumLeft = Math.max(maxPathSumLeft, 0);
maxPathSumRight = Math.max(maxPathSumRight, 0);
int localPathSumMaximum = maxPathSumLeft + maxPathSumRight + currentNode.val;
globalMaximumSum = Math.max(globalMaximumSum, localPathSumMaximum);
return Math.max(maxPathSumLeft, maxPathSumRight) + currentNode.val;
}
}