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
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
This method to this problem is similar to Unique Binary Search Trees.
public class Solution {
public ArrayList<TreeNode> generateTrees(int n) {
return treeHelp(1, n);
}
public ArrayList<TreeNode> treeHelp(int l, int n){
ArrayList<TreeNode> result = new ArrayList<TreeNode>();
if(l > n){ // no TreeNode can be generated
result.add(null);
return result;
}
else{
for(int i = l; i <= n; ++i){
ArrayList<TreeNode> leftNode = treeHelp(l, i - 1);
ArrayList<TreeNode> rightNode = treeHelp(i + 1, n);
for(int j = 0; j < leftNode.size(); ++j){
for(int m = 0; m < rightNode.size(); ++m){
TreeNode root = new TreeNode(i);
root.left = leftNode.get(j);
root.right = rightNode.get(m);
result.add(root);
}
}
}
}
return result;
}
}