Description
https://leetcode.com/problems/unique-binary-search-trees-ii/
给定n,生成所有结构上唯一的二叉搜索树,并返回所有这些树的root。
Solving Ideas
与Unique Binary Search Trees类似,不同的是,这里需要构造出所有结构上唯一的BST
实现起来比较简单就是使用 递归 的方法,遍历所有可能为root的情况,然后递归构建其左子树和右子树。
Solution
/**
* 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) {
if (n == 0) {
return new LinkedList<>();
}
return generate(1, n);
}
private LinkedList<TreeNode> generate(int start, int end) {
LinkedList<TreeNode> allTrees = new LinkedList<>();
if (start > end) {
allTrees.add(null);
return allTrees;
}
//pick up a root
for (int i = start; i <= end; i++) {
//all possible left subtrees if i is chosen to be a root
LinkedList<TreeNode> leftTrees = generate(start, i - 1);
//all possible right subtrees if i is chosen to be a root
LinkedList<TreeNode> rightTrees = generate(i + 1, end);
//connect left and right trees to the root i
for (TreeNode left : leftTrees) {
for (TreeNode right : rightTrees) {
TreeNode curTreeRoot = new TreeNode(i);
curTreeRoot.left = left;
curTreeRoot.right = right;
//put current tree root to the list
allTrees.add(curTreeRoot);
}
}
}
return allTrees;
}
}