I fell in a deadloop, and didn't see the actual recursion pattern.
Reference:http://fisherlei.blogspot.com/2013/03/leetcode-unique-binary-search-trees-ii.html
class Solution { public: vector<TreeNode *> generate(int s, int e) { vector<TreeNode *> subTree; if(s > e) { subTree.push_back(NULL); return subTree; } for(int i = s; i <= e; i++) { vector<TreeNode*> leftSubs = generate(s, i-1); vector<TreeNode*> rightSubs = generate(i+1, e); for(int j = 0; j < leftSubs.size(); j ++) for(int k = 0; k < rightSubs.size(); k ++) { TreeNode *pRoot = new TreeNode(i); pRoot->left = leftSubs[j]; pRoot->right= rightSubs[k]; subTree.push_back(pRoot); } } return subTree; } vector<TreeNode *> generateTrees(int n) { if(n == 0) return generate(1,0); return generate(1, n); } };