-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathUniqueBinarySearchTrees2.java
More file actions
35 lines (34 loc) · 1.03 KB
/
UniqueBinarySearchTrees2.java
File metadata and controls
35 lines (34 loc) · 1.03 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class UniqueBinarySearchTrees2 {
public List<TreeNode> generateTrees(int n) {
return buildTree(1, n);
}
public List<TreeNode> buildTree(int from, int to) {
List<TreeNode> list = new ArrayList<>();
if (from > to) {
list.add(null);
return list;
}
for (int mid = from; mid <= to; mid++) {
List<TreeNode> leftTrees = buildTree(from, mid - 1);
List<TreeNode> rightTrees = buildTree(mid + 1, to);
for (int i = 0; i < leftTrees.size(); i++) {
for (int j = 0; j < rightTrees.size(); j++) {
TreeNode root = new TreeNode(mid);
root.left = leftTrees.get(i);
root.right = rightTrees.get(j);
list.add(root);
}
}
}
return list;
}
}