Skip to content

Commit 7c84db5

Browse files
authored
Create 095. Unique Binary Search Trees II.java
1 parent a9f2754 commit 7c84db5

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// https://leetcode.com/problems/unique-binary-search-trees-ii
2+
3+
/**
4+
* Definition for a binary tree node.
5+
* public class TreeNode {
6+
* int val;
7+
* TreeNode left;
8+
* TreeNode right;
9+
* TreeNode(int x) { val = x; }
10+
* }
11+
*/
12+
public class Solution {
13+
public List<TreeNode> generate(int first, int last) {
14+
List<TreeNode> list = new ArrayList<>();
15+
16+
if (first > last) {
17+
list.add(null);
18+
} else if (first == last) {
19+
list.add(new TreeNode(first));
20+
} else {
21+
List<TreeNode> left = new ArrayList<>();
22+
List<TreeNode> right = new ArrayList<>();
23+
24+
for (int i = first; i <= last; i++) {
25+
left = generate(first, i - 1);
26+
right = generate(i + 1, last);
27+
28+
for (TreeNode l : left) {
29+
for (TreeNode r : right) {
30+
TreeNode root = new TreeNode(i);
31+
root.left = l;
32+
root.right = r;
33+
list.add(root);
34+
}
35+
}
36+
}
37+
}
38+
return list;
39+
}
40+
41+
public List<TreeNode> generateTrees(int n) {
42+
if (n == 0) return new ArrayList<TreeNode>();
43+
44+
return generate(1, n);
45+
}
46+
}

0 commit comments

Comments
 (0)