题目描述

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

相关文章:

  • 2021-06-20
  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-13
  • 2021-10-09
猜你喜欢
  • 2021-10-02
  • 2021-11-09
  • 2021-05-14
  • 2021-11-30
  • 2022-12-23
  • 2022-12-23
  • 2021-10-10
相关资源
相似解决方案