Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 10dc650

Browse files
refactor 124
1 parent 9c4db3d commit 10dc650

File tree

1 file changed

+46
-16
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+46
-16
lines changed

src/main/java/com/fishercoder/solutions/_124.java

+46-16
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,14 @@
22

33
import com.fishercoder.common.classes.TreeNode;
44

5+
import java.util.HashMap;
6+
import java.util.Map;
7+
58
/**
9+
* 124. Binary Tree Maximum Path Sum
610
* Given a binary tree, find the maximum path sum.
7-
8-
For this problem, a path is defined as any sequence of nodes from some starting node to any node
9-
in the tree along the parent-child connections.
11+
* For this problem, a path is defined as any sequence of nodes from some starting node to any node
12+
* in the tree along the parent-child connections.
1013
1114
The path must contain at least one node and does not need to go through the root.
1215
@@ -21,24 +24,51 @@
2124
*/
2225
public class _124 {
2326

24-
int max = Integer.MIN_VALUE;
25-
26-
public int maxPathSum(TreeNode root) {
27-
dfs(root);
28-
return max;
29-
}
27+
public static class Solution1 {
28+
int max = Integer.MIN_VALUE;
3029

31-
private int dfs(TreeNode root) {
32-
if (root == null) {
33-
return 0;
30+
public int maxPathSum(TreeNode root) {
31+
dfs(root);
32+
return max;
3433
}
3534

36-
int left = Math.max(dfs(root.left), 0);
37-
int right = Math.max(dfs(root.right), 0);
35+
private int dfs(TreeNode root) {
36+
if (root == null) {
37+
return 0;
38+
}
39+
40+
int left = Math.max(dfs(root.left), 0);
41+
int right = Math.max(dfs(root.right), 0);
3842

39-
max = Math.max(max, root.val + left + right);
43+
max = Math.max(max, root.val + left + right);
4044

41-
return root.val + Math.max(left, right);
45+
return root.val + Math.max(left, right);
46+
}
4247
}
4348

49+
public static class Solution2 {
50+
/**This one uses a map to cache, but surprisingly, it's 10% slower than all submissions compared with solution1*/
51+
int max = Integer.MIN_VALUE;
52+
53+
public int maxPathSum(TreeNode root) {
54+
Map<TreeNode, Integer> map = new HashMap<>();
55+
dfs(root, map);
56+
return max;
57+
}
58+
59+
private int dfs(TreeNode root, Map<TreeNode, Integer> map) {
60+
if (root == null) {
61+
return 0;
62+
}
63+
if (map.containsKey(root)) {
64+
return map.get(root);
65+
}
66+
int left = Math.max(0, dfs(root.left, map));
67+
int right = Math.max(0, dfs(root.right, map));
68+
max = Math.max(max, root.val + left + right);
69+
int pathSum = root.val + Math.max(left, right);
70+
map.put(root, pathSum);
71+
return pathSum;
72+
}
73+
}
4474
}

0 commit comments

Comments
 (0)