894. All Possible Full Binary Trees

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求
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.
这里写图片描述
给出树的节点的数量,找到所有可能的满二叉树的形式。

2,题目思路
对于这道题,可以利用递归的方法,依次寻找节点的左右孩子的形式。
用allPossibleFBT(i)和allPossibleFBT(N-i)的分别表示左子树和右子树。
左子树1个、3个、5个。。。右子树就是N-1个、N-3个、N-5个。。。
于是,用这种递归的办法,来找到所有符合条件的树。

3,程序源码

class Solution {
public:
    vector<TreeNode*> allPossibleFBT(int N) {
        vector<TreeNode*> res;
        if(N == 1)
        {
            res.push_back(new TreeNode(0));
            return res;
        }
        N--;
        for(int i = 1;i < N;i+=2)  //每次+2
        {
            vector<TreeNode*> ln = allPossibleFBT(i);  //递归部分
            vector<TreeNode*> rn = allPossibleFBT(N-i);
            for(TreeNode* ll : ln)
                for(TreeNode* rr : rn)
                {
                    TreeNode* node = new TreeNode(0);
                    node->left = ll;
                    node->right = rr;
                    res.push_back(node);
                }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值