I need to determine if the array is a valid min heap. And if it is not, which values are out of place? I am confused about heaps already, so this is difficult for me. Can anyone explain it to me, please?
[0, 6, 2, 26, 24, 22, 20, 48, 46, 44]
I need to determine if the array is a valid min heap. And if it is not, which values are out of place? I am confused about heaps already, so this is difficult for me. Can anyone explain it to me, please?
[0, 6, 2, 26, 24, 22, 20, 48, 46, 44]
In an array based min heap the items are stored in a full binary tree. Assuming a 0-based array, this means that the left child of the item in index i
would be in index 2i + 1
and the right child will be in index 2i + 2
.
The min heap invariant is that each node is smaller than its descendants. Therefore, in order to check whether the heap is a legal one all you need to do is to go through all the internal nodes and make sure that this condition holds, i.e. for each internal heap node in index i, a[i] < a[2*i + 1] && a[i] < a[2*i + 2]
.
Here is your heap in a more graphical form if that helps. The invariant is that each parent is less than both its children.
0
6 2
26 24 22 20
48 46 44
As you can see each node is greater than its parent so this is a valid min heap.