Simple and understandable Solution


#1
vector<TreeNode*> generate(int lo,int hi)
{
    vector<TreeNode*> cans;
    if(lo > hi)
    {
        cans.push_back(NULL);
        return cans;
    }
    for(int i=lo;i<=hi;i++)
    {
        vector<TreeNode*> l=generate(lo,i-1);
        vector<TreeNode*> r=generate(i+1,hi);
        for(int x=0;x<l.size();x++)
        {
            for(int y=0;y<r.size();y++)
            {
                TreeNode *node=new TreeNode(i);
                node->left=l[x];
                node->right=r[y];
                cans.push_back(node);
            }
        }
        l.clear();
        r.clear();
    }
    return cans;
}
vector<TreeNode*> Solution::generateTrees(int A) {
    return generate(1,A);
}

#2

Its a good approach, much shorter than mine & getting accepted. But dont you think you are missing some base cases. Like if root-node is 1. Then l.size() == 0 && r.size() != 0. So, the left sub-tree would but empty but not the right. But through your solution outer for loop wont run & the case would be missing. Same goes for root-node is n. Here, the inner for loop wont run & again the case would be missing.


#4

hey lakshya,
in generate method i have written an if condition(base condition: if(lo > hi) i’m pushing “NULL” into the vector. so the vector size will be 1. not 0.

thankyou,
bhanu prakash


#5

Hey BhanuPrakash!, you are a heavy driver.


#6

heavy driver dost…


#7

@ Achal_Parikh
Ssup?? buddy