Given two integers m and n where n >= m, find the total number of structurally correct Binary Search Trees (BSTs) possible that include all numbers between m and n (inclusive).
The number of BSTs with n nodes where n ranges from m to n can be calculated using Catalan numbers. The formula for the n-th Catalan number is given by:
$$
C_n = \frac{(2n)!}{(n+1)! \cdot n!}
$$
The number of structurally unique BSTs can also be computed using a recursive function. For each number within a given range [m, n], we consider the number as the root and recursively compute the number of possible left and right subtrees.
classSolution {
publicintnumTrees(int m, int n) {
int numKeys = n - m + 1;
return countTrees(numKeys);
}
privateintcountTrees(int numKeys) {
if (numKeys <= 1) {
return 1;
} else {
int sum = 0;
for (int root = 1; root <= numKeys; root++) {
int left = countTrees(root - 1);
int right = countTrees(numKeys - root);
sum += left * right;
}
return sum;
}
}
publicstaticvoidmain(String[] args) {
Solution sol =new Solution();
System.out.println(sol.numTrees(1, 3)); // Output: 5 System.out.println(sol.numTrees(2, 3)); // Output: 2 }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defnumTrees(self, m: int, n: int) -> int:
num_keys = n - m +1return self.count_trees(num_keys)
defcount_trees(self, n: int) -> int:
if n <=1:
return1 total =0for root in range(1, n +1):
left = self.count_trees(root -1)
right = self.count_trees(n - root)
total += left * right
return total
Using DP, we can iteratively solve for the number of unique BSTs with n nodes. We use an array to store the number of possible BSTs for each subtree size and build from the base cases up to the desired size.