解法一:递归

每一棵满二叉树的左右子树都是满二叉树。
用Map保存子问题的解和对偶数情况做剪枝参考官方题解:https://leetcode-cn.com/problems/all-possible-full-binary-trees/solution/suo-you-ke-neng-de-man-er-cha-shu-by-leetcode/

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. Map<Integer, List<TreeNode>> map = new HashMap<>();
  12. public List<TreeNode> allPossibleFBT(int N) {
  13. if (!map.containsKey(N)) {
  14. List<TreeNode> list = new LinkedList<>();
  15. if (N == 1) {
  16. TreeNode root = new TreeNode(0);
  17. list.add(root);
  18. } else if (N % 2 == 1) {
  19. for (int x = 0; x <= N - 1; ++x) {
  20. int y = N - 1 - x;
  21. for (TreeNode left : allPossibleFBT(x)) {
  22. for (TreeNode right : allPossibleFBT(y)) {
  23. TreeNode root = new TreeNode(0);
  24. root.left = left;
  25. root.right = right;
  26. list.add(root);
  27. }
  28. }
  29. }
  30. }
  31. map.put(N, list);
  32. }
  33. return map.get(N);
  34. }
  35. }