1 public class Solution { 2 public ArrayList<TreeNode> generateTrees(int n) { 3 // IMPORTANT: Please reset any member data you declared, as 4 // the same Solution instance will be reused for each test case. 5 return generate(1, n); 6 } 7 public ArrayList<TreeNode> generate(int start, int end){ 8 ArrayList<TreeNode> subTree = new ArrayList<TreeNode>(); 9 if(start > end){ 10 subTree.add(null); 11 return subTree; 12 } 13 14 for(int i = start; i <= end; i++){ 15 ArrayList<TreeNode> leftSubTree = generate(start, i - 1); 16 ArrayList<TreeNode> rightSubTree = generate(i + 1, end); 17 for(int j = 0; j < leftSubTree.size(); j++){ 18 for(int k = 0; k < rightSubTree.size(); k++){ 19 TreeNode node = new TreeNode(i); 20 node.left = leftSubTree.get(j); 21 node.right = rightSubTree.get(k); 22 subTree.add(node); 23 } 24 } 25 } 26 return subTree; 27 } 28 }