/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
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);
}
}
其实看了官方题解也没看太懂…
附上另一个大佬的解题思路:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<TreeNode> allPossibleFBT(int N) {
List<TreeNode> ans = new ArrayList<>();
// 满二叉树不能有偶数个节点
if(N%2==0){
return ans;
}
// 只有一个根节点的情况
if(N==1){
ans.add(new TreeNode(0));
}
// 除去根节点
N--;
// 左子树和右子树必须保证是两个奇数相加
for(int i = 1;i<N;i+=2){
List<TreeNode> leftTree = allPossibleFBT(i);
List<TreeNode> rightTree = allPossibleFBT(N-i);
for(TreeNode lnode:leftTree){
for(TreeNode rnode:rightTree){
TreeNode root = new TreeNode(0);
root.left = lnode;
root.right = rnode;
ans.add(root);
}
}
}
return ans;
}
}