根据节点数目构建满二叉树

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;
    }
};

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值