894. All Possible Full Binary Tree
A full binary tree is a binary tree where each node has exactly 0 or 2 children.
Return a list of all possible full binary trees with N
nodes. Each element of the answer is the root node of one possible tree.
Each node
of each tree in the answer must have node.val = 0
.
You may return the final list of trees in any order.
Example 1:
Input: 7 Output: [[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]] Explanation:
Note:
1 <= N <= 20
题解:从底层往顶层构建,例如当前需要构建节点数为5的满二叉树,那么可行的划分为:左子树1个,右子树3个;或者左子树3个,右子树1个;2-2的划分不合法。那么,当底层已经构建完成时,只需要枚举左、右子树的组合即可。
class Solution {
public:
vector<TreeNode*> allPossibleFBT(int N) {
vector<TreeNode*>ans;
if(N==1){
ans.push_back(new TreeNode(0));
return ans;
}
if(N%2==0) return ans; //偶数节点不能构成满二叉树
for(int i=1;i<N;i+=2){ //N=根节点+左子树为i个节点,右子树为N-1-i个节点,
if(N-1-i<1) continue;
auto left=allPossibleFBT(i);
auto right=allPossibleFBT(N-1-i);
for(auto&l:left){
for(auto&r:right){
auto tmp=new TreeNode(0);
tmp->left=l;
tmp->right=r;
ans.push_back(tmp);
}
}
}
return ans;
}
};