VOOZH about

URL: https://www.geeksforgeeks.org/dsa/total-number-of-bsts-using-array-elements/

⇱ Number of BSTs from each array element - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Number of BSTs from each array element

Last Updated : 14 Oct, 2025

Given an array arr[] of distinct integers. Find the number of Binary Search Trees that can be made using each element in arr[] as a root node.
Examples:

Input: arr[] = [2, 1, 3]
Output: [1, 2, 2] 
Explanation:

πŸ‘ 4

Input: arr[] = [2, 1]
Output: [1, 1]

Approach: Using Catalan numbers - O(n log(n)) Time and O(n) Space

If we pick node k as the root:

  • All nodes with values less than k must go to the left subtree.
  • All nodes with values greater than k must go to the right subtree.

The left and right subtrees themselves each must form valid BSTs, and their counts depend on how many nodes they contain.

Thus,

No. of BSTs rooted at k

= No. of BSTs with (k1) nodes on the left * No. of BSTs with (k2) nodes on the right

= T(k1) * T(k2)

such that T(i) denotes the number of BSTs with i distinct values.

where:
k1​ = number of elements less than k,
k2​ = number of elements greater than k, and
k1+k2=nβˆ’1

For a sorted list of nodes a1,a2,…,an​, each element acts as the root.
Thus, the total number of BSTs is:

T(n)=βˆ‘(i=1 to n) T(iβˆ’1)Γ—T(nβˆ’i)

This is because for element at index i( 1 ≀ i ≀ n), there are i-1 elements on left and n-i elements on right.

and T(0) = 1, T(1) = 1, as there is only one BST with either 0 or 1 element.

This recurrence is the same as that of the Catalan numbers, so the number of BSTs with n distinct nodes is Cn​.

Cn=βˆ‘(i=0 to nβˆ’1) CiΓ—C(nβˆ’1βˆ’i)

and, C0=1, C1 = 1.

Therefore, using this we can say that the number of BSTs with element k as the root node are:

C(i) * C(n-i-1)

where i is the the number of nodes with values less than k.


Output
1 2 2 
Comment