Skip to content

Commit c3cff36

Browse files
authored
Create Binary Trees With Factors.java
1 parent d250b89 commit c3cff36

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

Medium/Binary Trees With Factors.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
private final int MOD = 1_000_000_007;
3+
4+
public int numFactoredBinaryTrees(int[] arr) {
5+
int n = arr.length;
6+
Arrays.sort(arr);
7+
long[] dp = new long[n];
8+
Arrays.fill(dp, 1);
9+
Map<Integer, Integer> indexMap = new HashMap<>();
10+
for (int i = 0; i < n; i++) {
11+
indexMap.put(arr[i], i);
12+
}
13+
for (int i = 0; i < n; i++) {
14+
for (int j = 0; j < i; j++) {
15+
if (arr[i] % arr[j] == 0) {
16+
int right = arr[i] / arr[j];
17+
if (indexMap.containsKey(right)) {
18+
dp[i] = (dp[i] + dp[j] * dp[indexMap.get(right)]) % MOD;
19+
}
20+
}
21+
}
22+
}
23+
long result = 0;
24+
for (long count : dp) {
25+
result += count;
26+
}
27+
return (int) (result % MOD);
28+
}
29+
}

0 commit comments

Comments
 (0)