Consider a complete binary tree where the left and the right subtrees of the root are max-heaps. The lower bound for the number of operations to convert the tree to a heap is
(A) Ω(logn)
(B) Ω(n)
(C) Ω(nlogn)
(D) Ω(n2)
Answer: (A)
Explanation: The answer to this question is simply max-heapify function. Time complexity of max-heapify is O(Log n) as it recurses at most through height of heap.
// A recursive method to heapify a subtree with root at given index // This method assumes that the subtrees are already heapified void MinHeap::MaxHeapify(int i) { int l = left(i); int r = right(i); int largest = i; if (l < heap_size && harr[l] < harr[i]) largest = l; if (r < heap_size && harr[r] < harr[smallest]) largest = r; if (largest != i) { swap(&harr[i], &harr[largest]); MinHeapify(largest); } }
See Binary Heap for details.
Quiz of this Question