-
Notifications
You must be signed in to change notification settings - Fork 1
/
AllPossibleFullBinaryTrees.java
46 lines (37 loc) · 1.32 KB
/
AllPossibleFullBinaryTrees.java
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
package com.smlnskgmail.jaman.leetcodejava.medium;
import com.smlnskgmail.jaman.leetcodejava.support.TreeNode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
// https://leetcode.com/problems/all-possible-full-binary-trees/
public class AllPossibleFullBinaryTrees {
private static final Map<Integer, List<TreeNode>> VALUES = new HashMap<>();
private final int input;
public AllPossibleFullBinaryTrees(int input) {
this.input = input;
}
public List<TreeNode> solution() {
return allPossibleFBT(input);
}
private List<TreeNode> allPossibleFBT(int n) {
if (!VALUES.containsKey(n)) {
List<TreeNode> nodes = new ArrayList<>();
if (n == 1) {
nodes.add(new TreeNode(0));
} else if (n % 2 == 1) {
for (int i = 0; i < n; i++) {
int j = n - 1 - i;
for (TreeNode left : allPossibleFBT(i)) {
for (TreeNode right : allPossibleFBT(j)) {
TreeNode node = new TreeNode(0, left, right);
nodes.add(node);
}
}
}
}
VALUES.put(n, nodes);
}
return VALUES.get(n);
}
}