-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumProductOfSplitBinaryTree.java
More file actions
66 lines (58 loc) · 2.01 KB
/
MaximumProductOfSplitBinaryTree.java
File metadata and controls
66 lines (58 loc) · 2.01 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package solutions;
import datastructure.TreeNode;
import java.util.ArrayList;
import java.util.List;
// [Problem] https://leetcode.com/problems/maximum-product-of-splitted-binary-tree
class MaximumProductOfSplitBinaryTree {
List<Long> allSums = new ArrayList<>();
// DFS
// O(n) time, O(n) space
public int maxProduct(TreeNode root) {
long totalSum = calculateTreeSum(root);
long maxProduct = 0;
for (long sum : allSums) {
maxProduct = Math.max(sum * (totalSum - sum), maxProduct);
}
return (int) (maxProduct % 1000000007);
}
private long calculateTreeSum(TreeNode node) {
if (node == null) {
return 0;
}
long treeSum = node.val + calculateTreeSum(node.left) + calculateTreeSum(node.right);
allSums.add(treeSum);
return treeSum;
}
// Test
public static void main(String[] args) {
MaximumProductOfSplitBinaryTree solution = new MaximumProductOfSplitBinaryTree();
// Given input tree:
// 1
// / \
// 2 3
// / \ /
// 4 5 6
TreeNode input1 = new TreeNode(1,
new TreeNode(2, new TreeNode(4), new TreeNode(5)),
new TreeNode(3, new TreeNode(6), null));
int expectedOutput1 = 110;
int actualOutput1 = solution.maxProduct(input1);
System.out.println("Test 1 passed? " + (expectedOutput1 == actualOutput1));
// Given input tree:
// 1
// \
// 2
// / \
// 3 4
// / \
// 5 6
TreeNode input2 = new TreeNode(1,
null,
new TreeNode(2,
new TreeNode(3),
new TreeNode(4, new TreeNode(5), new TreeNode(6))));
int expectedOutput2 = 110;
int actualOutput2 = solution.maxProduct(input2);
System.out.println("Test 2 passed? " + (expectedOutput2 == actualOutput2));
}
}