Unique Binary Search Trees II
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
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public ArrayList<TreeNode> generateTrees(int n) { 3 return builder(1,n); 4 } 5 public ArrayList<TreeNode> builder(int start,int end){ 6 ArrayList<TreeNode> sub = new ArrayList<TreeNode>(); 7 if(start>end){ 8 sub.add(null); 9 return sub; 10 } 11 for(int i=start;i<=end;i++){ 12 ArrayList<TreeNode> left = builder(start,i-1); 13 ArrayList<TreeNode> right = builder(i+1,end); 14 for(int j=0;j<left.size();j++){ 15 for(int k=0;k<right.size();k++){ 16 TreeNode root = new TreeNode(i); 17 root.left = left.get(j); 18 root.right = right.get(k); 19 sub.add(root); 20 } 21 } 22 } 23 return sub; 24 } 25 }