Unique Binary Search Trees *

Givenn, how many structurally uniqueBST's(binary search trees) that store values 1...n?

For example, Givenn= 3, there are a total of 5 unique BST's.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

Solution: Let count[i] be the number of unique binary search trees for i. The number of trees are determined by the number of subtrees which have different root node

F[0] = 1 ,

F[1] = 1 , when 1 is root as F[1] = F[0] * F[0]

F[2] = F[0] * F[1] when root is 1 then left null and right there are only 1 numbers left

      F\[1\]  \* F\[0\] when root is 2 then left contains 1 digits and right is null so.
class Solution(object):
    def numTrees(self, n):
        if n <= 0:
            return 0
        F = [0] * (n + 1)

        F[0] = 1
        F[1] = 1

        for i in range(2, n + 1):
            for j in range(0, i):
                F[i] += F[j] * F[i - j - 1]
        return F[n]

Last updated

Was this helpful?