Given 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
这道题和一唯一的不同在于要求返回所有的树,所以需要知道几个特性
1. [1,2,3,4,...i-1,i,i+1...n]这样的数组中,以i为根节点,[1~i-1]为左子树,[i+1~n]为右子树所构造出来的BST具有唯一性
2. 每一个数建立左节点一定在左子树里找,建立右节点一定在右子树里找,就不会出错
代码如下
public ArrayList<TreeNode> generateTrees(int n) {
return helper(1, n);
}
private ArrayList<TreeNode> helper(int left, int right) {
ArrayList<TreeNode> result = new ArrayList<TreeNode>();
if (left > right) {
result.add(null);
return result;
}
for (int i = left; i <= right; i++) {
ArrayList<TreeNode> leftSub = helper(left, i - 1);
ArrayList<TreeNode> rightSub = helper(i + 1, right);
for (int j = 0; j < leftSub.size(); j++) {
for (int k = 0; k < rightSub.size(); k++) {
TreeNode root = new TreeNode(i);
root.left = leftSub.get(j);
root.right = rightSub.get(k);
result.add(root);
}
}
}
return result;
}