-
Notifications
You must be signed in to change notification settings - Fork 1
/
0095.cpp
43 lines (36 loc) · 1.02 KB
/
0095.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
TreeNode* add(TreeNode* root, int value)
{
if (!root)
return new TreeNode(value);
if (value < root->val)
root->left = add(root->left, value);
else
root->right = add(root->right, value);
return root;
}
string flatten(TreeNode* root)
{
if (!root)
return "";
return "L" + flatten(root->left) + "V" + to_string(root->val) + "R" + flatten(root->right);
}
public:
vector<TreeNode*> generateTrees(int n) {
vector<int> nums;
for (int i = 1; i <= n; i++)
nums.push_back(i);
map<string, TreeNode*> trees;
do
{
TreeNode* root = nullptr;
for (auto n : nums)
root = add(root, n);
trees[flatten(root)] = root;
} while (next_permutation(nums.begin(), nums.end()));
vector<TreeNode*> result;
for (auto t : trees)
result.push_back(t.second);
return result;
}
};