Copy **Input:** n = 3
**Output:** [[1,null,2,null,3],[1,null,3,2],[2,1,3],[3,1,null,null,2],[3,2,null,1]]
Copy **Input:** n = 1
**Output:** [[1]]
Copy /**
* 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 > generateTrees ( int n) {
// Edge cases: n < 1
if (n < 1 ) return new ArrayList <>();
return generate( 1 , n) ;
}
private List < TreeNode > generate ( int start , int end) {
List < TreeNode > res = new ArrayList <>();
// Exit
if (start > end) {
res . add ( null );
}
// Iterate
for ( int i = start; i <= end; i ++ ) {
List < TreeNode > left = generate(start , i - 1 ) ;
List < TreeNode > right = generate(i + 1 , end) ;
for ( TreeNode l : left) {
for ( TreeNode r : right) {
res . add ( new TreeNode(i , l , r) );
}
}
}
return res;
}
}
Copy class Solution {
Map < String , List < TreeNode >> cache = new HashMap <>();
public List < TreeNode > generateTrees ( int n) {
// Edge cases: n < 1
if (n < 1 ) return new ArrayList <>();
return generate( 1 , n) ;
}
private List < TreeNode > generate ( int start , int end) {
if ( cache . containsKey (start + "-" + end)) {
return cache . get (start + "-" + end);
}
List < TreeNode > res = new ArrayList <>();
// Exit
if (start > end) {
res . add ( null );
}
// Iterate
for ( int i = start; i <= end; i ++ ) {
List < TreeNode > left = generate(start , i - 1 ) ;
List < TreeNode > right = generate(i + 1 , end) ;
for ( TreeNode l : left) {
for ( TreeNode r : right) {
res . add ( new TreeNode(i , l , r) );
}
}
}
cache . put (start + "-" + end , res);
return res;
}
}