Complete the code to create a min heap by choosing the correct comparison operator.
func (h MinHeap) Less(i, j int) bool {
return h[i] [1] h[j]
}In a min heap, the parent node is smaller than its children, so we use the less than operator < to compare.
Complete the code to create a max heap by choosing the correct comparison operator.
func (h MaxHeap) Less(i, j int) bool {
return h[i] [1] h[j]
}In a max heap, the parent node is greater than its children, so we use the greater than operator > to compare.
Fix the error in the code to pop the root element from a min heap.
func (h *MinHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[[1]]
*h = old[0 : n-1]
return x
}The root element of a heap is always at index 0, so we pop old[0].
Fill both blanks to build a min heap from a slice of integers.
h := MinHeap[1] heap.Init(&h) return h[2]
We assign the slice 'data' to the heap struct and return the heap struct with the data inside curly braces.
Fill all three blanks to push a new value into a max heap and maintain heap property.
func (h *MaxHeap) Push(x interface{}) {
*h = append(*h, [1])
heap.[2](h)
}
func (h *MaxHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[[3]]
*h = old[0 : n-1]
return x
}We append the new value x, then call heap.Push to maintain the heap property, and pop the root at index 0.