给定一个整数 n,生成所有由 1 ... n 为节点所组成的 二叉搜索树 。
示例:
输入:3
输出:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
解释:
以上的输出对应以下 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
提示:
0 <= n <= 8
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<TreeNode> generateTrees(int n) {
if(n == 0) {return new ArrayList<TreeNode>();}
return help(1,n);
}
private List<TreeNode> help(int start , int end){
List<TreeNode> list = new ArrayList<>();
if(start > end) {list.add(null);return list;}
if (start == end){list.add(new TreeNode(start));return list;}
for(int i = start ;i<=end ; i++){
List<TreeNode> leftList = help(start,i-1);
List<TreeNode> rightList = help(i+1,end);
for(TreeNode leftnode : leftList){
for(TreeNode rightnode : rightList){
TreeNode node = new TreeNode(i);
node.left = leftnode;
node.right = rightnode;
list.add(node);
}
}
}
return list;
}
}