I guess one more way of doing this would be to keep the count of all child elements for each node in the Tree. Since the main aim of the Binary heap is to be completely balanced, you can decide to insert the new node or they key, either towards the left or the right depending upon which side the tree is less balanced.
I am currently trying to write the Binary Hep code using Java and am stuck at this very same point. I have come up with this approach of balancing my Heap as well as solve the problem of where to insert the new node. This should still maintain the complexities of the Heap implementation.
Will post the code in sometime. If someone sees any issues with this or think that this is not the right way to do it, please do correct me.
Update: Here's the code (https://gist.github.com/naveenwashere/5607516):
public class BinaryHeap {
//Later you can implement a resizable array logic.
int[] bH;
public BinaryHeap(int N)
{
bH = new int[N + 1];
}
//Index of the root
int k = 1;
//The APIs
public void put(int key)
{
//Place the element at the end of the array
bH[this.k] = key;
if(bH[this.k] > bH[this.k/2])
{
//since the elements in an array implementation of the binary heap is put at the end of the array,
//we must always check if the property of the tree holds true or not.
swim(this.k);
}
this.k++;
}
public void deleteMax()
{
//Replace the element in the root with the element at the end of the array
bH[1] = bH[k];
//Restore the order of the tree
sink(1);
this.k--;
}
public void deleteMin()
{
bH[this.k - 1] = 0;
this.k--;
}
public void swim(int k)
{
while((k != 1) && (bH[k] > bH[k/2]))
{
swap(k, k/2);
k = k/2;
}
}
public void sink(int k)
{
while(2*k <= this.k)
{
int j = 2*k;
if(max(j, j+1)) j++;
if(bH[k] < bH[j])
swap(k, j);
else if(bH[k] > bH[j])
break;
k = j;
}
}
private boolean max(int i, int j) {
if(bH[i] < bH[j])
return true;
return false;
}
private void swap(int i, int j) {
int temp = 0;
temp = bH[i];
bH[i] = bH[j];
bH[j] = temp;
}
private void printAll() {
for(int i=1; i < this.k; i++)
{
System.out.print(bH[i] + " ");
}
System.out.println();
}
public static void main(String[] args) throws Exception
{
int a[] = {6,5,7,8,2,9,8,1};
BinaryHeap bh = new BinaryHeap(a.length);
for(int i=0; i < a.length; i++)
{
bh.put(a[i]);
}
System.out.println("Elements in Binary Heap: ");
bh.printAll();
System.out.println("Deleting Minimum: ");
bh.deleteMin();
bh.printAll();
System.out.println("Deleting Maximum: ");
bh.deleteMax();
bh.printAll();
}}
Thanks,
~N