95. Unique Binary Search Trees II
1 public List<TreeNode> generateTrees(int n) { 2 List<TreeNode> res = new ArrayList<TreeNode>(); 3 if(n <= 0) { 4 return res; 5 } 6 return helper(1, n); 7 } 8 9 private List<TreeNode> helper(int left, int right) { 10 List<TreeNode> res = new ArrayList<TreeNode>(); 11 if(left > right) { 12 res.add(null); 13 return res; 14 } 15 for(int i = left; i <= right; i++) { 16 List<TreeNode> leftList = helper(left, i-1); 17 List<TreeNode> rightList = helper(i+1, right); 18 for(int j = 0; j < leftList.size(); j++) { 19 for(int k = 0; k < rightList.size(); k++) { 20 TreeNode root = new TreeNode(i); 21 root.left = leftList.get(j); 22 root.right = rightList.get(k); 23 res.add(root); 24 } 25 } 26 } 27 return res; 28 }