Consider a complete binary tree where the left and the right subtrees ...
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);
}
}
View all questions of this test
Consider a complete binary tree where the left and the right subtrees ...
Nlogn
b) n
c) n^2
d) nloglogn
Answer: b) n
Explanation:
In a max-heap, the parent node is always greater than or equal to its children. In order to convert the given complete binary tree to a max-heap, we can follow the following steps:
1. Compare the root node with its left and right children. If the root node is greater than both its children, we are done. Otherwise, swap the root node with the larger of its two children.
2. Recursively apply step 1 to the subtree that was swapped with the root node.
Since we are given that the left and right subtrees of the root are already max-heaps, we only need to perform step 1 once for the root node. This will result in the largest element being at the root node, but the left and right subtrees may no longer be max-heaps. However, since each subtree has at most n/2 nodes, we can recursively apply step 1 to each subtree in O(n) time.
Therefore, the lower bound for the number of operations to convert the tree to a heap is O(n).