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)