/**
* 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 LinkedList<>();
return build(1, n);
}
// 辅助函数,构造闭区间 [lo, hi] 组成的 BST
List<TreeNode> build(int lo, int hi) {
List<TreeNode> ans = new LinkedList<>();
// base case
if (lo > hi) {
ans.add(null);
return ans;
}
// 1、穷举 root 节点的所有可能。
for (int mid = lo; mid <= hi; mid++) {
// 2、递归构造出左右子树的所有合法 BST。
List<TreeNode> leftTree = build(lo, mid - 1);
List<TreeNode> rightTree = build(mid + 1, hi);
// 3、给 root 节点穷举所有左右子树的组合。
for (TreeNode left : leftTree) {
for (TreeNode right : rightTree) {
// mid 作为根节点 root 的值
TreeNode root = new TreeNode(mid);
root.left = left;
root.right = right;
ans.add(root);
}
}
}
return ans;
}
}