Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
Idea: Each time we choose a key, in the range of [i,j] as the root. Then call generator(i,k-10) and generator(k+1, j) to get the all the possible left subtrees LEFT, and right subtrees RIGHT. Then we just list all the combination (leftsubtree, rightsubtree), and add the root to the result list RST.
VERSION 1 [WONG]
public class Solution {
public List<TreeNode> generateTrees(int n) {
return generator(1, n);
}
private List<TreeNode> generator(int l, int h) {
ArrayList<TreeNode> rst = new ArrayList<>();
if (l > h) {
rst.add(null);
} else if (l == h) {
rst.add(new TreeNode(l));
} else {
for (int k = l; k <= h; k++) {
<span style="color:#FF0000;">TreeNode root = new TreeNode(k);</span>
List<TreeNode> left = generator(l, k - 1);
List<TreeNode> right = generator(k + 1, h);
for(TreeNode ln : left){
for(TreeNode rn : right){
root.left = ln;
root.right = rn;
rst.add(root);
}
}
}
}
return rst;
}
}
Input:3
Output:[{1,#,3,2},{1,#,3,2},{2,1,3},{3,2,#,1},{3,2,#,1}]
Expected:[{1,#,2,#,3},{1,#,3,2},{2,1,3},{3,1,#,#,2},{3,2,#,1}]
REASON: if we create the root node outside the two for loops:
for(TreeNode ln : left){
for(TreeNode rn : right){
we only create one node for all the conbination for that node! OBJECT is add to rst BY REFERENCE.
VERSION2 [CORRECT]:
public class UniqueBinarySearchTreesII {
public List<TreeNode> generateTrees(int n) {
return generator(1, n);
}
private List<TreeNode> generator(int l, int h) {
ArrayList<TreeNode> rst = new ArrayList<>();
if (l > h) {
rst.add(null);
} else if (l == h) {
rst.add(new TreeNode(l));
} else {
for (int k = l; k <= h; k++) {
List<TreeNode> left = generator(l, k - 1);
List<TreeNode> right = generator(k + 1, h);
for(TreeNode ln : left){
for(TreeNode rn : right){
<span style="color:#FF0000;"> TreeNode root = new TreeNode(k);</span>
root.left = ln;
root.right = rn;
rst.add(root);
}
}
}
}
return rst;
}