问题
I am trying to implement that checks whether a given array is a heap.
public static boolean Heap(int[] A)
{
for (int i = 1; i <= (A.length - 2) / 2; i++) {
if (A[i] < A[2 * i] || A[i] < A[2 * i + 1]) {
return false;
}
}
return true;
}
A = {50, 45, 40, 35, 20, 25, 20};
B = {45, 50, 40, 35, 20, 25, 20};
if (Heap(A)) {
System.out.println("Heap");
} else {
System.out.println("Not a heap");
}
When I call the function for the arrays above, they both return true, while B should have been caught in the if statement if (A[i] < A[2 * i]...
What am I doing wrong?
回答1:
Perhaps this is what you want:
public static void main(String... args) {
int[] A = {50, 45, 40, 35, 20, 25, 20};
int[] B = {45, 50, 40, 35, 20, 25, 20};
System.out.println(isMaxHeap(A));
System.out.println(isMaxHeap(B));
}
private static boolean isMaxHeap(int[] arr) {
int N = arr.length;
for (int i = (N - 2) / 2; i > -1; --i) { // start from the first internal node who has children;
int j = 2 * i + 1; // the left child;
if (j < N - 1 && arr[i] < arr[j+1]) j++; // select the bigger child;
if (arr[i] < arr[j]) return false; // if parent is smaller than the child;
}
return true;
}
But do please show some efforts next time before asking.
回答2:
The bottom-up solution is simple: check each node to see that it's not greater than its parent. For a min-heap, change the >
to <
:
for (int i = a.length-1; i > 0; --i)
{
int parent = (i-1)/2;
if (a[i] > a[parent]) return false;
}
return true;
You'll often see the recursive solution:
bool isMaxHeap(int[] a)
{
return isMaxHeap(a, 0);
}
bool isMaxHeap(int[] a, int ix)
{
int leftChild = (ix*2)+1;
if (leftChild < a.length)
{
if (a[leftChild] > a[ix]) return false;
if (!isMaxHeap(a, leftChild) return false;
}
int rightChild = leftChild+1;
if (rightChild < a.length)
{
if (a[rightChild] > a[ix]) return false;
if (!isMaxHeap(a, rightChild) return false;
}
return true;
}
The idea here is that in a heap, every subtree is also a heap. So we check the top level, then check each branch of the tree. We apply that recursively.
来源:https://stackoverflow.com/questions/51584921/java-check-if-array-is-heap