Skip to content

Commit b6e619e

Browse files
committed
update 0124 Solution for Java
1 parent c1ec89c commit b6e619e

File tree

1 file changed

+14
-13
lines changed
  • solution/0100-0199/0124.Binary Tree Maximum Path Sum

1 file changed

+14
-13
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
class Solution {
2-
private int max = Integer.MIN_VALUE;
2+
private int val = Integer.MIN_VALUE;
3+
34
public int maxPathSum(TreeNode root) {
4-
helper(root);
5-
return max;
5+
dfs(root);
6+
return val;
67
}
7-
private int helper(TreeNode root) {
8-
if (root == null) return 0;
9-
if (root.left == null && root.right == null) {
10-
max = Math.max(max, root.val);
11-
return root.val;
8+
9+
public int dfs(TreeNode root) {
10+
if (root == null) {
11+
return 0;
1212
}
13-
int left = helper(root.left);
14-
int right = helper(root.right);
15-
int currSum = Math.max(Math.max(left + root.val, right + root.val), root.val);
16-
max = Math.max(Math.max(currSum, left + right + root.val), max);
17-
return currSum;
13+
int left = Math.max(0, dfs(root.left));
14+
int right = Math.max(0, dfs(root.right));
15+
int val1 = root.val + left + right;
16+
int val2 = root.val + Math.max(0, Math.max(left, right));
17+
val = Math.max(val, val1);
18+
return val2;
1819
}
1920
}

0 commit comments

Comments
 (0)