-
Notifications
You must be signed in to change notification settings - Fork 78
/
solution.cpp
57 lines (53 loc) · 1.26 KB
/
solution.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
* 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 createTree(1,n);
}
vector<TreeNode *> createTree(int start, int end)
{
vector<TreeNode *> results;
if(start>end)
{
results.push_back(NULL);
return results;
}
for(int k=start;k<=end;k++)
{
vector<TreeNode *> left = createTree(start,k-1);
vector<TreeNode *> right = createTree(k+1,end);
for(int i=0;i<left.size();i++)
{
for(int j=0;j<right.size();j++)
{
TreeNode * root = new TreeNode(k);
root->left = left[i];
root->right = right[j];
results.push_back(root);
}
}
}
return results;
}
void dfs(TreeNode *root)
{
if(root == NULL)
return;
else
{
cout<< root->val << " ";
dfs(root->left);
dfs(root->right);
}
}
};