-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathAll_Possible_Full_Binary_Trees.cpp
49 lines (43 loc) · 1.37 KB
/
All_Possible_Full_Binary_Trees.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
/**
* 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 {
vector<TreeNode*> allPossibleFBT(int n, vector<TreeNode*>& result) {
if(n == 0) {
result.push_back(nullptr);
return result;
}
if(n % 2 == 0) {
return vector<TreeNode*>();
}
for(int i = 1; i <= n; i++) {
int leftTreeNodeCount = i - 1;
int rightTreeNodeCount = n - i;
vector<TreeNode*> leftSubTrees;
allPossibleFBT(leftTreeNodeCount, leftSubTrees);
vector<TreeNode*> rightSubTrees;
allPossibleFBT(rightTreeNodeCount, rightSubTrees);
for(TreeNode* leftSubTree : leftSubTrees) {
for(TreeNode* rightSubTree : rightSubTrees) {
TreeNode* root = new TreeNode(0);
root->left = leftSubTree;
root->right = rightSubTree;
result.push_back(root);
}
}
}
return result;
}
public:
vector<TreeNode*> allPossibleFBT(int N) {
vector<TreeNode*> result;
allPossibleFBT(N, result);
return result;
}
};