-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path95.cpp
More file actions
25 lines (24 loc) · 731 Bytes
/
Copy path95.cpp
File metadata and controls
25 lines (24 loc) · 731 Bytes
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
class Solution {
public:
vector<TreeNode *> generateTrees(int n) {
return n ? traverse(1, n) : vector<TreeNode *>();
}
vector<TreeNode *> traverse(int m, int n) {
if (m > n)
return {nullptr};
vector<TreeNode *> trees;
for (int i = m; i <= n; ++i) {
vector<TreeNode *> left = traverse(m, i - 1);
vector<TreeNode *> right = traverse(i + 1, n);
for (auto &l:left) {
for (auto &r:right) {
auto root = new TreeNode(i);
root->left = l;
root->right = r;
trees.push_back(root);
}
}
}
return trees;
}
};