30 ms c++ solution

• ``````/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<TreeNode *> generateTrees(int n) {
return helper(1,n);
}

vector<TreeNode*> helper(int s, int e) {
if (s > e) {
return vector<TreeNode*>(1,NULL);
}

vector<TreeNode*> result;
for (int i=s; i <= e; ++i) {
vector<TreeNode*> left, right;
left = helper(s,i-1);
right = helper(i+1,e);
for (int j = 0; j < left.size(); ++j) {
for (int k = 0; k < right.size(); ++k) {
TreeNode* root = new TreeNode(i);
root->left = left[j];
root->right = right[k];
result.push_back(root);
}
}
}

return result;
}
};``````

• Always find recursion tricky for me, just can't get the meaning of this code

• This post is deleted!

• what is the space and time complexity?>

• Nice and easy understand, thank you.

• I can only understand others' recursive code by list recursion nodes, it is hard to write by myself

• how do you free up space for the `new` root nodes?

And why you have to create the run this line below in the inner most loop each time, rather than one time per `i`?

``TreeNode* root = new TreeNode(i);``

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