[leetcode] problem 894 – all possible full binary trees

A full binary tree is a binary tree where each node has exactly 0 or 2 children.

Return a list of all possible full binary trees with N nodes. Each element of the answer is the root node of one possible tree.

Each node of each tree in the answer must have node.val = 0.

You may return the final list of trees in any order.

Example

Input: 7

Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]

Explanation:

m9spdS.png

Note

  • 1 <= N <= 20

Code

1
2
3
4
5
6
public class  {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
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
private Map<Integer, List<TreeNode>> map = new HashMap<>();

public List<TreeNode> allPossibleFBT(int N) {
List<TreeNode> result = new ArrayList<>();

if (N == 1) {
result.add(new TreeNode(0));
return result;
}
else if (N % 2 == 0)
return result;

if (map.containsKey(N))
return map.get(N);

for (int i = 1; i < N; i += 2) {
List<TreeNode> left = allPossibleFBT(i);
List<TreeNode> right = allPossibleFBT(N - i - 1);

for (TreeNode l : left) {
for (TreeNode r : right) {
TreeNode root = new TreeNode(0);
root.left = l;
root.right = r;
result.add(root);
}
}
}

map.put(N, result);

return result;
}