Question
Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
Solution
Key to the solution is to divide the problem into two sub-problems. Unlike "Unique Binary Search Trees", this problem is NP-hard.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<TreeNode> generateTrees(int n) {
return generateTreesHelper(1, n);
}
private List<TreeNode> generateTreesHelper(int start, int end) {
List<TreeNode> result = new ArrayList<TreeNode>();
if (start > end) {
result.add(null);
return result;
}
for (int i = start; i <= end; i++) {
List<TreeNode> lefts = generateTreesHelper(start, i - 1);
List<TreeNode> rights = generateTreesHelper(i + 1, end);
for (TreeNode left : lefts) {
for (TreeNode right : rights) {
TreeNode tmp = new TreeNode(i);
tmp.left = left;
tmp.right = right;
result.add(tmp);
}
}
}
return result;
}
}