-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUniqueBinarySearchTreesII.java
More file actions
47 lines (41 loc) · 995 Bytes
/
UniqueBinarySearchTreesII.java
File metadata and controls
47 lines (41 loc) · 995 Bytes
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
39
40
41
42
43
44
45
46
47
package com.mirraico.leetcode;
import java.util.*;
public class UniqueBinarySearchTreesII {
public List<TreeNode> dfs(int l, int r) {
List<TreeNode> tmpAns = new ArrayList<TreeNode>();
if(l == r) {
tmpAns.add(new TreeNode(l));
return tmpAns;
} else if(l > r) {
tmpAns.add(null);
return tmpAns;
}
List<TreeNode> lAns, rAns;
for(int i = l; i <= r; i++) {
lAns = this.dfs(l, i - 1);
rAns = this.dfs(i + 1, r);
for(int j = 0; j < lAns.size(); j++) {
for(int k = 0; k < rAns.size(); k++) {
TreeNode tmpRoot = new TreeNode(i);
tmpRoot.left = lAns.get(j);
tmpRoot.right = rAns.get(k);
tmpAns.add(tmpRoot);
}
}
}
return tmpAns;
}
public List<TreeNode> generateTrees(int n) {
if(n == 0) return new ArrayList<TreeNode>();
return this.dfs(1, n);
}
public static void main(String[] args) {
new Solution().generateTrees(3);
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}