95. Unique Binary Search Trees II
class Solution { public List<TreeNode> generateTrees(int n) { if(n==0) return new ArrayList<TreeNode>(); return generateTrees(1, n); } private List<TreeNode> generateTrees(int i, int j) { List<TreeNode> res=new ArrayList<TreeNode>(); if(i>j) res.add(null); else { for(int k=i;k<=j;k++) { List<TreeNode> left=generateTrees(i,k-1); List<TreeNode> right=generateTrees(k+1,j); for(TreeNode l:left) for(TreeNode r:right) { TreeNode node=new TreeNode(k); node.left=l; node.right=r; res.add(node); } } } return res; } }