Reputation: 1794
I'm studying for my final, and am not sure if I am inserting the values 6, 7, 57, 54, 96, 3, 9, 4, 2, 8, 32
properly. I end up with a tree looking like:
96
/ \
57 9
/ \ / \
6 54 3 7
/ \ / \
4 2 8 32
Can anyone tell me if this is correct, or if it's not point out where I messed up? Thanks!
Upvotes: 0
Views: 773
Reputation: 9237
Yes you're solution is correct
As long as you add the new element at the end of the list which represents a binary heap, then apply heapify on that element.
Heapify should compare the element with its' parent and if it is greater, it should swap these elements and keep going until you reach the root.
here are some stages:
6 --> 7 --> 57
/ / \
6 6 7
Here is a java example:
public class BinaryMinHeap {
public void insert(int value) {
if (heapSize == data.length)
throw new HeapException("Heap's underlying storage is overflow");
else {
heapSize++;
data[heapSize - 1] = value;
heapify(heapSize - 1);
}
}
…
private void heapify(int nodeIndex) {
int parentIndex, tmp;
if (nodeIndex != 0) {
parentIndex = getParentIndex(nodeIndex);
if (data[parentIndex] < data[nodeIndex]) {
tmp = data[parentIndex];
data[parentIndex] = data[nodeIndex];
data[nodeIndex] = tmp;
heapify(parentIndex);
}
}
}
}
code source: here
Upvotes: 1