[LeetCode] Problem 95 - Unique Binary Search Trees II

Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1 … n.

Example

Input: 3

Output:

1
2
3
4
5
6
7
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]

Explanation:
The above output corresponds to the 5 unique BST’s shown below:

1
2
3
4
5
1         3     3      2      1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

Code

1
2
3
4
5
6
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
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
public List<TreeNode> generateTrees(int n) {   
if (n == 0)
return new ArrayList<>();

return generate(1, n);
}

private List<TreeNode> generate(int start, int end) {
List<TreeNode> result = new ArrayList<>();

if (start > end) {
result.add(null);
return result;
}

for (int i = start; i <= end; i++) {
List<TreeNode> leftList = generate(start, i - 1);
List<TreeNode> rightList = generate(i + 1, end);

for (TreeNode left : leftList) {
for (TreeNode right : rightList) {
TreeNode root = new TreeNode(i);
root.left = left;
root.right = right;
result.add(root);
}
}
}

return result;
}