-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution095.java
58 lines (49 loc) · 1.26 KB
/
Solution095.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package algorithm.leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* @author: mayuan
* @desc: 不同的二叉搜索树 II
* @date: 2019/02/19
*/
public class Solution095 {
public List<TreeNode> generateTrees(int n) {
if (0>=n){
return new ArrayList<>();
}
return dfs(1, n);
}
public List<TreeNode> dfs(int start, int end) {
List<TreeNode> ans = new ArrayList<>();
if (start > end) {
ans.add(null);
return ans;
}
if (start == end) {
ans.add(new TreeNode(start));
return ans;
}
List<TreeNode> left = null, right = null;
for (int i = start; i <= end; ++i) {
left = dfs(start, i - 1);
right = dfs(i + 1, end);
for (TreeNode lnode : left) {
for (TreeNode rnode : right) {
TreeNode root = new TreeNode(i);
root.left = lnode;
root.right = rnode;
ans.add(root);
}
}
}
return ans;
}
private class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}