1) Initialize list of BSTs as empty.
2) For every number i where i varies from 1 to N, do following
......a) Create a new node with key as 'i', let this node be 'node'
......b) Recursively construct list of all left subtrees.
......c) Recursively construct list of all right subtrees.
3) Iterate for all left subtrees
a) For current leftsubtree, iterate for all right subtrees
Add current left and right subtrees to 'node' and add
'node' to list.
For a sorted sequence: 1 ... n, construct BST:
select i in the sequence
sub sequence 1 ... (i - 1) on the left
sub sequence (i+1) ... n on the right
construct the sub tree from the sub sequence recursively
class Solution {
public int numTrees(int n) {
if (n < 2) return 1;
int[] uniqueTrees = new int[n + 1];
uniqueTrees[0] = 1;
uniqueTrees[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 1; j <= i; j++) {
uniqueTrees[i] += uniqueTrees[j - 1] * uniqueTrees[i - j];
}
}
return uniqueTrees[n];
}
}
class Solution {
public int numTrees(int n) {
// Note: we should use long here instead of int, otherwise overflow
long C = 1;
for (int i = 0; i < n; ++i) {
C = C * 2 * (2 * i + 1) / (i + 2);
}
return (int) C;
}
}