![]() |
VOOZH | about |
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]
If we pick node k as the root:
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.
1 2 2