Simple and understandable Solution

vector<TreeNode*> generate(int lo,int hi)
    vector<TreeNode*> cans;
    if(lo > hi)
        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);
    return cans;
vector<TreeNode*> Solution::generateTrees(int A) {
    return generate(1,A);


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.


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.

bhanu prakash


Hey BhanuPrakash!, you are a heavy driver.


heavy driver dost…


@ Achal_Parikh
Ssup?? buddy