LeetCode: 894. All Possible Full Binary Trees

题目:894. All Possible Full Binary Trees(https://leetcode.com/problems/all-possible-full-binary-trees/description/).

这个问题是典型的递归问题,首先读题之后可知有性质“完全二叉树结点个数必定为奇数”。所以问题变简单了点,如果输入N为偶数,直接输出空List即可。

对于一个有n个结点的完全二叉树,其可以分解为有i个结点(i为奇数)的左子树和n-i-1个结点的右子树,所以只需遍历i的取值即可!

class Solution {
    public List<TreeNode> allPossibleFBT(int N) {
        List<TreeNode> res = new ArrayList<>();
        if (N == 1) {
            res.add(new TreeNode(0));
            return res;
        }
        if (N % 2 == 0) {
            return res;
        }
        for (int i = 1; i < N; i = i + 2) {
            List<TreeNode> lns = allPossibleFBT(i);
            List<TreeNode> rns = allPossibleFBT(N - i - 1);
            for (TreeNode ln : lns) {
                for (TreeNode rn : rns) {
                    TreeNode head = new TreeNode(0);
                    head.left = ln;
                    head.right = rn;
                    res.add(head);
                }
            }
        }
        return res;
    }
}

 

 

感谢:https://leetcode.com/problems/all-possible-full-binary-trees/discuss/164134/C%2B%2B-solution-easy-to-understand-and-use-chinese%3A)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值