Skip to content

Commit 7eb090d

Browse files
Create All possible full binary tree.cpp
1 parent 9a49125 commit 7eb090d

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

Diff for: LeetCode/All possible full binary tree.cpp

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution {
2+
public:
3+
vector<TreeNode*> allPossibleFBT(int n) {
4+
5+
if(n&1 == 0)return {}; //FBT can have only odd number of nodes
6+
if(n == 1)return {new TreeNode()};
7+
8+
vector<TreeNode*>res;
9+
10+
for(int i = 1; i < n-1;i+=2){ //incrementation by 2 to avoid redundant recursive call for even number of nodes
11+
12+
vector<TreeNode*>left = allPossibleFBT(i);
13+
vector<TreeNode*>right = allPossibleFBT(n-i-1); //1 is reserved for root node, hence n-i-1
14+
15+
for(auto l : left)
16+
for(auto r : right)
17+
TreeNode* root = new TreeNode(), root->left = l, root->right = r, res.push_back(root);
18+
}
19+
20+
return res;
21+
22+
}
23+
};

0 commit comments

Comments
 (0)