Created
March 23, 2022 14:08
-
-
Save ravichandrae/9d989567ee7ece883fdee5317d18f8bc to your computer and use it in GitHub Desktop.
Given a number of nodes, count how many BSTs we can construct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def countBST(n): | |
""" | |
:param n: a positive integer | |
:return: Number of all possible binary search trees (BST) with n unique numbers | |
The number is called a Catalan number F(n) = C(2*n, n) / (n+1) = (2*n)! / (n+1)! * n! | |
As the above formula involves calculating factorial which is laborious and can overflow in some cases, | |
We can use the following recurrence relation to make the calculation simple. | |
F(0) = 1 | |
F(n+1) = (2*(2*n + 1) / (n+2)) * F(n) | |
""" | |
result = 1 | |
for i in range(1, n): | |
result = 2 * (2 * i + 1) * result // (i + 2) | |
return result | |
def main(): | |
n = int(input("How many nodes? ")) | |
print("Number of BSTs: {}".format(countBST(n))) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment