So i\'m trying to implement a binary min heap. I understand what the binary min heap entails in terms of it\'s structure and it\'s properties. However I\'m hitting a wall when I
I had the same homework assignment. The solution I found is to step down your binary tree level by level, each time deciding to make a left or a right turn depending on the number of nodes at the bottom. I made a recursive algorithm for this.
For example, say you want to place a new node in the following tree:
A
/ \
B C
/ \ / \
D E X X
Starting at the top, you find that there are 2/4 full nodes at the bottom. Therefore you descend via the right branch and find yourself at the top of the tree with root C. At the bottom of this tree there are 0/2 full nodes, so you descend via the left branch and find yourself at a leaf node, so that is where you place the new element.
Here is the Java code I used to calculate the height of a tree, the number of possible nodes at the bottom of a tree with any given height, and the number of full or "used" nodes at the bottom of a tree with size size.
private int height(int size) {
return (int) Math.ceil(log2(size + 1));
}
// returns the amount of space in the bottom row of a binary tree
private int bottomRowSpace(int height) {
return (int) Math.pow(2, height - 1);
}
// returns the amount of filled spots in the bottom row of a binary tree
private int bottomRowFilled(int size) {
return size - (bottomRowSpace(height(size)) - 1);
}
// log base2
private double log2(double a) {
return Math.log(a) / Math.log(2);
}