Complete the code to create a Min Heap by choosing the correct comparison operator.
class MinHeap { heap: number[] = []; insert(value: number) { this.heap.push(value); this.bubbleUp(this.heap.length - 1); } bubbleUp(index: number) { while (index > 0) { const parentIndex = Math.floor((index - 1) / 2); if (this.heap[index] [1] this.heap[parentIndex]) { [this.heap[index], this.heap[parentIndex]] = [this.heap[parentIndex], this.heap[index]]; index = parentIndex; } else { break; } } } }
In a Min Heap, the child node should be smaller than the parent node to maintain the heap property. So, we swap when the child is less than the parent.
Complete the code to create a Max Heap by choosing the correct comparison operator.
class MaxHeap { heap: number[] = []; insert(value: number) { this.heap.push(value); this.bubbleUp(this.heap.length - 1); } bubbleUp(index: number) { while (index > 0) { const parentIndex = Math.floor((index - 1) / 2); if (this.heap[index] [1] this.heap[parentIndex]) { [this.heap[index], this.heap[parentIndex]] = [this.heap[parentIndex], this.heap[index]]; index = parentIndex; } else { break; } } } }
In a Max Heap, the child node should be greater than the parent node to maintain the heap property. So, we swap when the child is greater than the parent.
Fix the error in the code that removes the root from a Min Heap by choosing the correct method to restore heap property.
class MinHeap { heap: number[] = []; removeRoot() { if (this.heap.length === 0) return null; const root = this.heap[0]; this.heap[0] = this.heap.pop()!; this.[1](0); return root; } bubbleDown(index: number) { // Implementation omitted } }
After removing the root, we need to restore the heap property by moving the new root down if needed. This is done by 'bubbleDown'.
Fill both blanks to complete the condition that decides when to swap nodes during bubbleDown in a Max Heap.
bubbleDown(index: number) {
const left = 2 * index + 1;
const right = 2 * index + 2;
let largest = index;
if (left < this.heap.length && this.heap[left] [1] this.heap[largest]) {
largest = left;
}
if (right < this.heap.length && this.heap[right] [2] this.heap[largest]) {
largest = right;
}
if (largest !== index) {
[this.heap[index], this.heap[largest]] = [this.heap[largest], this.heap[index]];
this.bubbleDown(largest);
}
}In a Max Heap, during bubbleDown, we swap with the child that is greater than the current node to maintain the heap property.
Fill all three blanks to create a function that returns the root element of a Min Heap without removing it.
peek(): number | null {
if (this.heap.length === 0) {
return [1];
}
return this.heap[[2]];
// The root is at index [3]
}If the heap is empty, we return null. The root element is always at index 0 in a heap.