Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1
\ / / / \
3 2 1 1 3 2
/ / \
2 1 2 3
题意:这是96题的followup,要求返回的不只是方案个数了,而是具体的方案列表。
思路:
按照96题自开始的思路,求出每个点为根节点的方案list,然后merge到总list中。
对于每一个数字作为根节点的情况,对它左边和右边的数字仍然递归调用方法,生成它左右BST的list,最后通过两次循环就可以得到这个数字作为根节点时,总共的方案集合了。
public List<TreeNode> generateTrees(int n) {
return helper(1, n);
}
public List<TreeNode> helper(int start, int end) {
List<TreeNode> res = new ArrayList<>();
if (start > end) {
res.add(null);
return res;
}
if (start == end) {
res.add(new TreeNode(start));
return res;
}
List<TreeNode> left = new ArrayList<>();
List<TreeNode> right = new ArrayList<>();
for (int i = start; i <= end; i++) {
//TreeNode root = new TreeNode(i);//bug
left = helper(start, i - 1);
right = helper(i + 1, end);
for (TreeNode lt : left) {
for (TreeNode rt : right) {
TreeNode root = new TreeNode(i);
root.left = lt;
root.right = rt;
res.add(root);
}
}
}
return res;
}