I need to find a number of different binary search trees over n elements. I know, that the number of binary search trees over n distinct elements is Catalan number. But what if numbers can repeat? In Binary Search Tree elements of left subtree are less than root, and elements of right subtree are equal or greater than root.
This is my code for calculating a number of different binary search trees over n elements. I calculate this number by modulo 123456789, as it can be really big. Can I simply change it to solve my problem?
#include <algorithm>
#include <vector>
#include <iostream>
#include <limits>
using std::vector;
using std::cin;
using std::cout;
using std::endl;
long long countTreeDP(int nodeNumber)
{
vector <vector<long long> > cNumbers;
for (int i = 0; i < nodeNumber + 2; ++i)
{
vector<long long> cur(nodeNumber + 2, 0);
cNumbers.push_back(cur);
}
for (int i = 0; i < nodeNumber + 2; ++i)
{
cNumbers[i][0] = 1;
}
long long sum = 0;
for (int i = 1; i < nodeNumber + 1; ++i)
{
sum = 0;
for (int j = 1; j <= i; ++j)
{
long long numFirst = cNumbers[nodeNumber + 1][i - j] % 123456789;
long long numSecond = cNumbers[nodeNumber + 1][j - 1] % 123456789;
cNumbers[j][i] = (numFirst * numSecond) % 123456789;
sum += cNumbers[j][i];
sum = sum % 123456789;
}
cNumbers[nodeNumber+1][i] = sum;
}
return cNumbers[nodeNumber+1][nodeNumber];
}
int main()
{
vector<long long> nodesValues;
int size = 0;
cin >> size;
for (int i = 0; i < size; ++i)
{
long long elem;
cin >> elem;
nodesValues.push_back(elem);
}
std::sort(nodesValues.begin(), nodesValues.end());
int uniqueCount = 0;
for (int i = 1; i < nodesValues.size(); ++i)
{
if (nodesValues[i] != nodesValues[i-1])
++uniqueCount;
}
cout << countTreeDP(uniqueCount + 1) << endl;
system("pause");
return 0;
}
cNumbers[a][b]entry into words? If so, does that help you in answering your own question? Would I be correct in assuming that you will provide the sequence of tree node values as input, so that one can check which are distinct and which are equal? - MvG