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)

猜你喜欢

转载自blog.csdn.net/majinliang1234/article/details/83150759