-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetcode095.java
49 lines (42 loc) · 1.3 KB
/
Leetcode095.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
//DP问题,给定n,则有n种可能的root取值,然后两边重复操作
public List<TreeNode> generateTrees(int n) {
if (n == 0)
return new ArrayList<TreeNode>();
return uniqueBST(1, n);
}
public List<TreeNode> uniqueBST(int start, int end) {
List<TreeNode> ans = new ArrayList<TreeNode>();
if (start > end) {
ans.add(null);
return ans;
}
if (start == end) {
TreeNode head = new TreeNode(start);
ans.add(head);
return ans;
}
for (int i=start; i<=end; i++) {
List<TreeNode> left = uniqueBST(start, i-1);
List<TreeNode> right = uniqueBST(i+1, end);
for (TreeNode leftNode : left) {
for (TreeNode rightNode : right) {
TreeNode head = new TreeNode(i);
head.left = leftNode;
head.right = rightNode;
ans.add(head);
}
}
}
return ans;
}
}