(1)递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<TreeNode*> helper(int start,int end) {
if(start>end) return {nullptr};
vector<TreeNode*> v;
for(int i=start;i<=end;i++) {
vector<TreeNode*> left_v=helper(start,i-1);
vector<TreeNode*> right_v=helper(i+1,end);
for(int m=0;m<left_v.size();m++) {
for(int n=0;n<right_v.size();n++) {
TreeNode *root=new TreeNode(i);
root->left=left_v[m];
root->right=right_v[n];
v.push_back(root);
}
}
}
return v;
}
vector<TreeNode*> generateTrees(int n) {
return helper(1,n);
}
};