Program to count number of BST with n nodes in Python

Suppose we have n different nodes, all distinct. We need to find how many ways we can arrange them to form a Binary Search Tree (BST). In a BST, the left subtree always holds smaller values and the right subtree holds greater values.

To solve this problem, we use Catalan numbers. The Catalan number C(n) represents the number of structurally different binary search trees with n different keys.

Catalan Number Formula

The formula for the nth Catalan number is:

C(n) = (2n)! / ((n+1)! × n!)

Alternatively, it can be calculated as:

C(n) = C(2n, n) / (n+1)

Where C(2n, n) is the binomial coefficient "2n choose n".

Example with n = 3

For n = 3 nodes, we can form 5 different BSTs:

Tree 1 1 2 3 Tree 2 1 3 2 Tree 3 2 1 3 Tree 4 3 1 2 Tree 5 3 2 1

Algorithm Steps

To solve this problem, we follow these steps:

  • Define a function ncr(n, r) to calculate binomial coefficient
  • Calculate C(2*n, n) using the binomial coefficient
  • Return C(2*n, n) / (n+1) to get the nth Catalan number

Implementation

def ncr(n, r):
    """Calculate binomial coefficient C(n, r)"""
    res = 1
    if r > n - r:
        r = n - r
    
    for i in range(r):
        res *= (n - i)
        res //= (i + 1)
    
    return res

def count_bst(n):
    """Count number of BSTs with n nodes using Catalan number"""
    if n <= 1:
        return 1
    
    c = ncr(2 * n, n)
    return c // (n + 1)

# Test with different values
for n in range(1, 6):
    result = count_bst(n)
    print(f"n = {n}: {result} BSTs")
n = 1: 1 BSTs
n = 2: 2 BSTs
n = 3: 5 BSTs
n = 4: 14 BSTs
n = 5: 42 BSTs

Alternative Implementation Using Recursion

We can also calculate Catalan numbers using the recursive formula:

def count_bst_recursive(n):
    """Calculate Catalan number using recursion with memoization"""
    if n <= 1:
        return 1
    
    catalan = [0] * (n + 1)
    catalan[0], catalan[1] = 1, 1
    
    for i in range(2, n + 1):
        for j in range(i):
            catalan[i] += catalan[j] * catalan[i - 1 - j]
    
    return catalan[n]

# Test the recursive approach
n = 3
result = count_bst_recursive(n)
print(f"Number of BSTs with {n} nodes: {result}")
Number of BSTs with 3 nodes: 5

Time Complexity

  • Binomial coefficient approach: O(n) time, O(1) space
  • Dynamic programming approach: O(n²) time, O(n) space

Conclusion

The number of structurally different BSTs with n nodes equals the nth Catalan number. We can calculate it efficiently using the binomial coefficient formula C(2n,n)/(n+1), which provides the count of all possible BST arrangements.

Updated on: 2026-03-26T15:49:53+05:30

393 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements