| 17 | }; |
| 18 | |
| 19 | class Solution { |
| 20 | public: |
| 21 | vector<TreeNode*> generateTrees(int n) { |
| 22 | if (n == 0) return vector<TreeNode*> {}; |
| 23 | deque < TreeNode * > q; |
| 24 | TreeNode * first = new TreeNode(1); |
| 25 | q.push_back(first); |
| 26 | for (int i=2; i<=n; i ++) { // i is the element to add |
| 27 | int size = q.size(); |
| 28 | for(int _=0; _<size; _ ++) { |
| 29 | TreeNode * f = q.front(); |
| 30 | q.pop_front(); |
| 31 | TreeNode * hdr = new TreeNode(-1); |
| 32 | hdr->right = f; |
| 33 | int cnt = 0; |
| 34 | while (true) { |
| 35 | TreeNode * newtree = deepcopy(hdr); |
| 36 | TreeNode * p = newtree; |
| 37 | int incnt = 0; |
| 38 | while (incnt++ < cnt and p->right != NULL) p = p->right; |
| 39 | if (p != NULL and incnt == cnt + 1) { |
| 40 | cnt ++; |
| 41 | TreeNode * append = new TreeNode(i); |
| 42 | append->left = p->right; |
| 43 | p->right = append; |
| 44 | q.push_back(newtree->right); |
| 45 | } else { |
| 46 | break; |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | vector< TreeNode * > res (make_move_iterator(q.begin()), make_move_iterator(q.end())); |
| 52 | return res; |
| 53 | } |
| 54 | |
| 55 | TreeNode * deepcopy(TreeNode * root) { |
| 56 | if (root == NULL) return NULL; |
| 57 | TreeNode * p = new TreeNode(root->val); |
| 58 | p->left = deepcopy(root->left); |
| 59 | p->right = deepcopy(root->right); |
| 60 | return p; |
| 61 | } |
| 62 | }; |
| 63 | |
| 64 | int main() { |
| 65 | Solution s; |
nothing calls this directly
no outgoing calls
no test coverage detected