Java:
class Solution {
public List<TreeNode> generateTrees(int n) {
if(n==0) return new ArrayList<>();
return genTrees(1,n);
}
public List<TreeNode> genTrees(int a, int b){
List<TreeNode> res = new ArrayList<TreeNode>();
if (a>b){
res.add(null);
return res;
}
if (a==b){
res.add(new TreeNode(a));
return res;
}
List<TreeNode> left,right;
for(int i=a;i<=b;i++){
left = genTrees(a, i-1);
right = genTrees(i+1, b);
for(TreeNode l:left){
for(TreeNode r:right){
TreeNode root = new TreeNode(i);
root.left = l;
root.right = r;
res.add(root);
}
}
}
return res;
}
}
Python:
class Solution:
def generateTrees(self, n):
"""
:type n: int
:rtype: List[TreeNode]
"""
def genNode(val, left, right):
node = TreeNode(val)
node.left = left
node.right = right
return node
def genTrees(a, b):
return [genNode(root, left, right)
for root in range(a, b+1)
for left in genTrees(a, root-1)
for right in genTrees(root+1, b)] or [None]
if n == 0:
return []
return genTrees(1, n)