Number of binary search trees over n distinct elements

后端 未结 3 1154
青春惊慌失措
青春惊慌失措 2020-12-05 01:24

How many binary search trees can be constructed from n distinct elements? And how can we find a mathematically proved formula for it?

Example:

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 01:32

    Let T(n) be the number of bsts of n elements.

    Given n distinct ordered elements, numbered 1 to n, we select i as the root.

    This leaves (1..i-1) in the left subtree for T(i-1) combinations and (i+1..n) in the right subtree for T(n-i) combinations.

    Therefore:

    T(n) = sum_i=1^n(T(i-1) * T(n-i))
    

    and of course T(1) = 1

提交回复
热议问题