894. All Possible Full Binary Trees(所有可能的完美二叉树)

题目描述

894. All Possible Full Binary Trees(所有可能的完美二叉树)894. All Possible Full Binary Trees(所有可能的完美二叉树)894. All Possible Full Binary Trees(所有可能的完美二叉树)

方法思路

class Solution {
    //Runtime: 3 ms, faster than 95.78%
    //Memory Usage: 44 MB, less than 68.95% 
    Map<Integer, List<TreeNode>> memo = new HashMap();
    public List<TreeNode> allPossibleFBT(int N) {
        if (!memo.containsKey(N)) {
            List<TreeNode> ans = new LinkedList();
            if (N == 1) {
                ans.add(new TreeNode(0));
            } else if (N % 2 == 1) {
                for (int x = 0; x < N; ++x) {
                    int y = N - 1 - x;
                    for (TreeNode left: allPossibleFBT(x))
                        for (TreeNode right: allPossibleFBT(y)) {
                            TreeNode bns = new TreeNode(0);
                            bns.left = left;
                            bns.right = right;
                            ans.add(bns);
                        }
                }
            }
            memo.put(N, ans);
        }

        return memo.get(N);
    }
}