Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The number of binary trees can be calculated using the <a href="http://en.wikipedia.org/wiki/Catalan_number">catalan number</a>.</p> <p>The number of binary search trees can be seen as a recursive solution. i.e., Number of binary search trees = (Number of <strong>Left</strong> binary search sub-trees) * (Number of <strong>Right</strong> binary search sub-trees) * (Ways to choose the root)</p> <p>In a BST, only the relative ordering between the elements matter. So, without any loss on generality, we can assume the distinct elements in the tree are <em>1, 2, 3, 4, ...., n</em>. Also, let the number of BST be represented by <em>f(n) for n elements</em>.</p> <p>Now we have the multiple cases for choosing the root.</p> <ol> <li>choose 1 as root, <em>no</em> element can be inserted on the left sub-tree. <em>n-1</em> elements will be inserted on the right sub-tree.</li> <li>Choose 2 as root, <em>1</em> element can be inserted on the left sub-tree. <em>n-2</em> elements can be inserted on the right sub-tree.</li> <li>Choose 3 as root, <em>2</em> element can be inserted on the left sub-tree. <em>n-3</em> elements can be inserted on the right sub-tree.</li> </ol> <p>...... Similarly, for <em>i-th</em> element as the root, <em>i-1</em> elements can be on the left and <em>n-i</em> on the right.</p> <p>These sub-trees are itself BST, thus, we can summarize the formula as:</p> <p><strong><em>f(n) = f(0)f(n-1) + f(1)f(n-2) + .......... + f(n-1)f(0)</em></strong></p> <p>Base cases, f(0) = 1, as there is exactly 1 way to make a BST with 0 nodes. f(1) = 1, as there is exactly 1 way to make a BST with 1 node.</p> <p><img src="https://i.stack.imgur.com/5N3C7.gif" alt="Final Formula"></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload