没什么思路。。emmm,想到的有首先如果当结点数目>3,第一层肯定是一个根节点,第二层是两个子节点;如果一个节点的左孩子不为空,右孩子应该也不为空;在左子树和右子树不一样的时候,可以互换左右子树又可以得到一个新的树;我猜应该可以递归构建树;如果剩下的节点数为偶数,那么已构建的结点孩子数应该是0或者2,如果剩下的节点数是奇数,那么一定存在一个节点孩子数为1。除了这些,就想不到其他的什么了。。。。
看了其他人的solution,说实话,没太看懂。。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private Map<Integer,List<TreeNode>> cache = new HashMap<>();
public List<TreeNode> allPossibleFBT(int N) {
List<TreeNode> res = new ArrayList<>();
if( cache.containsKey( N ) )return cache.get( N );
if( N == 1 ){
res.add( new TreeNode( 0 ));
}
else if( N % 2 == 1 ){
for( int i = 0 ; i < N ; i ++ ){
int j = N - 1 - i ;
List<TreeNode> left = allPossibleFBT( i );
List<TreeNode> right = allPossibleFBT( j );
for( TreeNode l : left ){
for( TreeNode r : right ){
TreeNode root = new TreeNode( 0 );
root.left = l;
root.right = r;
res.add( root );
}
}
}
}
cache.put( N , res );
return cache.get( N );
}
}
照着别人的solution写,一开始RTE了,好像是nullPointers之类的错误,我不知道为啥,就又对照了一遍,加了一个判断条件if( N % 2 == 1 ),就Accepted了,