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.
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
Solution 1: Divide and conquer. In order to generate 1...n, we can choose any of them to be root, let us say i, root.left is from list of 0...i-1 and root.right is from list of i+1...n. Code as below:
public class Solution {
public List<TreeNode> generateTrees(int n) {
return generate(1,n);
}
private List<TreeNode> generate(int lo, int hi) {
List<TreeNode> res=new ArrayList<>();
if (lo>hi) res.add(null);
else {
for (int i=lo; i<=hi; i++) {
for (TreeNode l: generate(lo,i-1)) {
for (TreeNode r: generate(i+1,hi)) {
TreeNode x=new TreeNode(i);
x.left=l;
x.right=r;
res.add(x);
}
}
}
}
return res;
}
}
没有评论:
发表评论