-
Notifications
You must be signed in to change notification settings - Fork 16
/
UniqueBinarySearchTreesII.java
38 lines (35 loc) · 1.15 KB
/
UniqueBinarySearchTreesII.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
import java.util.ArrayList;
import java.util.List;
public class UniqueBinarySearchTreesII {
public static List<TreeNode> generateTrees(int n) {
List<TreeNode>[] result = new List[n + 1];
result[0] = new ArrayList<>();
if (n == 0) {
return result[0];
}
result[0].add(null);
for (int len = 1; len <= n; len++) {
result[len] = new ArrayList<>();
for (int j = 0; j < len; j++) {
for (TreeNode nodeL : result[j]) {
for (TreeNode nodeR : result[len - j - 1]) {
TreeNode node = new TreeNode(j + 1);
node.left = nodeL;
node.right = clone(nodeR, j + 1);
result[len].add(node);
}
}
}
}
return result[n];
}
private static TreeNode clone(TreeNode n, int offset) {
if (n == null) {
return null;
}
TreeNode node = new TreeNode(n.val + offset);
node.left = clone(n.left, offset);
node.right = clone(n.right, offset);
return node;
}
}