File tree 1 file changed +46
-0
lines changed
1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments