GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

How many min/max heaps can be constructed with numbers 1 to N ?

asked Aug 17, 2015 by koustavc

3 Answers

 
Best answer

The minimum (in case of min heap) element has to be placed at the root of the heap.  After that we split up the remaining elements into the two subtrees and 
recursively compute the number of binary heaps that they can make.  The main part here is that the two subtrees don't have necessarily the same number of nodes 
(leaving complete binary tree case)

We fill the tree in such order that nodes in the lowest level will go to the left subtree first and then any excess nodes will be in the 
right subtree.  To compute the number of nodes in each subtree we first need to compute height of the tree.  This can be calculated as the largest power of two no 
larger than N , 2k.  Then there must be M = 1+N−2k nodes in the bottom level of the tree.

With that you can calculate the number of elements in the left subtree as

L = 2^(k−1) − 1 + min(2^(k−1) , M)

and the right subtree as

R = 2^(k−1) − 1 + max(0,M − 2^(k-1))

so the number of binary heaps with N distinct elements, will be
f(N) = (N−1 C L) * f(L) * f(R)
 

answered Aug 17, 2015 by utkarsh111
selected Aug 17, 2015 by koustavc
Can you tell me how did you arrive at L = 2^(k−1) − 1 + min(2^(k−1) , M) and also the expression for R?

Check out this reference, well explained, read it, : https://www.quora.com/How-many-Binary-heaps-can-be-made-from-N-distinct-elements

answered Aug 17, 2015 by Mr.Lazy

Below are some useful observations about heaps using N numbers

1) Min/Max number will always be at root.

2) All heaps must have same structure as elements are filled level by level and from left to right.

Examples:

Different Min Heaps for N  = 5

      1
    /   \
   2     3
  / \
 4   5

      1
    /   \
   2     3
  / \
 5   4

      1
    /   \
   3     2
  / \
 4   5  

      1
    /   \
   3     2
  / \
 5   4  

 

answered Aug 17, 2015 by Lokesh
...