A simple solution with C++


  • 0
    2

    class Solution {
    public:
    vector<TreeNode*> generateTrees(int n) {
    vector<TreeNode*> res;
    if(n==0) return res;
    res=generate(1,n);
    return res;
    }
    vector<TreeNode*> generate(int start,int end)
    {
    vector<TreeNode*> res;
    if(start>end){ TreeNode* p=NULL; res.push_back(p); return res;}
    for(int i=start;i<=end;i++)
    {
    vector<TreeNode*> left=generate(start,i-1);
    vector<TreeNode*> right=generate(i+1,end);
    for(int m=0;m<left.size();m++)
    {
    for(int n=0;n<right.size();n++)
    {
    TreeNode* root=new TreeNode(i);
    root->left=left[m];
    root->right=right[n];
    res.push_back(root);
    }
    }
    }
    return res;
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.