-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUnique_Binary_Tree.cpp
More file actions
42 lines (42 loc) · 1013 Bytes
/
Copy pathUnique_Binary_Tree.cpp
File metadata and controls
42 lines (42 loc) · 1013 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for a binary tree node.
* 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) {
vector<TreeNode*> res;
if(n == 0) return res;
return helper(1, n);
}
vector<TreeNode*> helper(int left, int right)
{
vector<TreeNode*> res; res.clear();
if(left > right)
{
res.push_back(NULL);
return res;
}
for(int i = left; i <= right; i++)
{
vector<TreeNode*> leftVector = helper(left, i - 1);
vector<TreeNode*> rightVector = helper(i + 1, right);
for(int j = 0; j < leftVector.size(); j++)
{
for(int k = 0; k < rightVector.size(); k++)
{
TreeNode* root = new TreeNode(i);
root->left = leftVector[j];
root->right = rightVector[k];
res.push_back(root);
}
}
}
return res;
}
};