classSolution:defgenerateTrees(self,n:int) -> List[TreeNode]:ifnot n:return []defgenerateTree(start,end):if start > end:return [None] res = []for i inrange(start, end +1): ls =generateTree(start, i -1) rs =generateTree(i +1, end)for l in ls:for r in rs: node =TreeNode(i) node.left = l node.right = r res.append(node)return resreturngenerateTree(1, n)
CPP Code:
class Solution {
private:
vector<TreeNode*> generateTrees(int first, int last) {
if (first > last) return { NULL };
vector<TreeNode*> v;
for (int i = first; i <= last; ++i) {
auto lefts = generateTrees(first, i - 1);
auto rights = generateTrees(i + 1, last);
for (auto left : lefts) {
for (auto right : rights) {
v.push_back(new TreeNode(i));
v.back()->left = left;
v.back()->right = right;
}
}
}
return v;
}
public:
vector<TreeNode*> generateTrees(int n) {
if (n <= 0) return {};
return generateTrees(1, n);
}
};