712527. Convert Min Heap to Max Heap
Convert Min Heap to Max Heap
Summary
This problem involves converting a min heap into a max heap. A min heap is a complete binary tree where each node is smaller than its children, and a max heap is a complete binary tree where each node is larger than its children. The conversion process should maintain the heap property of the resulting max heap.
Detailed Explanation
To convert a min heap to a max heap, we can use a similar approach as the min heap construction algorithm. The key idea is to swap each node with its largest child, starting from the last non-leaf node and moving towards the root. This process ensures that the nodes are rearranged in a way that maintains the max heap property.
Here's a step-by-step breakdown of the solution:
- Start from the last non-leaf node (i.e., the parent of the leaf nodes) and move towards the root.
- For each node, find its largest child. If the node has only one child or no children, it is already a max heap node, so skip to the next step.
- Compare the current node with its largest child. If the child is larger, swap them. Otherwise, continue to the next node.
- Repeat steps 1-3 until you reach the root node.
The time complexity of this algorithm is O(n), where n is the number of nodes in the heap. This is because we visit each node once and perform a constant amount of work for each node. The space complexity is O(1), as we only use a small amount of extra memory to store temporary variables.
Optimized Solutions
Java
public class MinToMaxHeap {
public static void convertMinToMaxHeap(int[] arr) {
int n = arr.length;
for (int i = (n / 2) - 1; i >= 0; i--) {
int maxIndex = findLargestChild(arr, i);
if (maxIndex != -1) {
swap(arr, i, maxIndex);
}
}
}
private static int findLargestChild(int[] arr, int parentIndex) {
int leftChildIndex = 2 * parentIndex + 1;
int rightChildIndex = 2 * parentIndex + 2;
if (leftChildIndex >= arr.length || rightChildIndex >= arr.length) {
return -1; // no child
} else if (arr[leftChildIndex] > arr[rightChildIndex]) {
return leftChildIndex;
} else {
return rightChildIndex;
}
}
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}