Trees With Limited Keys

How many distinct binary search trees can be created out of 4 distinct keys?

7 14 24 28 42

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Satyabrata Dash
Jul 8, 2016

Relevant wiki: Binary Search Trees

Here is a systematic way to enumerate these BSTs (binary search trees). Consider all possible binary search trees with each element at the root. If there are n n nodes, then for each choice of root node, there are n 1 n - 1 non-root nodes and these non-root nodes must be partitioned into those that are less than a chosen root and those that are greater than the chosen root.

Let’s say node i is chosen to be the root. Then there are i 1 i - 1 nodes smaller than i i and n i n - i nodes bigger than i i . For each of these two sets of nodes, there is a certain number of possible subtrees.

Let t ( n ) t(n) be the total number of BSTs with n nodes. The total number of BSTs with i at the root is t ( i 1 ) t ( n i ) t(i - 1) t(n - i) . The two terms are multiplied together because the arrangements in the left and right subtrees are independent. That is, for each arrangement in the left tree and for each arrangement in the right tree, you get one BST with i at the root.

Summing over i gives the total number of binary search trees with n nodes.

The base case is t ( 0 ) = 1 t(0) = 1 and t ( 1 ) = 1 t(1) = 1 , i.e. there is one empty BST and there is one BST with one node.

Great Question !

Hritesh Mourya - 4 years, 11 months ago

Log in to reply

ohh! thanks.

Satyabrata Dash - 4 years, 11 months ago

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...