1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
class Solution { public List<TreeNode> generateTrees(int n) { if (n == 0) { return new ArrayList<>(); } return helper(1, n); }
private List<TreeNode> helper(int start, int end) { List<TreeNode> result = new ArrayList<>(); if (start > end) { result.add(null); } for (int i = start; i <= end; i++) { List<TreeNode> leftList = helper(start, i - 1); List<TreeNode> rightList = helper(i + 1, end);
for (TreeNode left : leftList) { for (TreeNode right : rightList) { TreeNode root = new TreeNode(i); root.left = left; root.right = right; result.add(root); } } } return result; } }
|