How do we check if an array represents a heap data structure recursively?
Assume it is an array of integers, and I am checking for max heap.
The following is what I came up with, but I don’t know if that is correct.
public static boolean isHeap(int[] arr) {
if (arr = null)
return false;
return isHeapTree(arr, 0);
}
private static boolean isHeapTree(int[] arr, int i) {
if (i = arr.length - 1)
return true;
// check if a parent's value is larger or equal to both of
// its left child and right child
else if (arr[i] >= arr[2i + 1] && arr[i] >= arr[2i + 2])
return (isHeapTree(arr, 2i + 1) && isHeapTree(arr, 2i + 2));
else
return false;
}
is it possible a binary heap could be incomplete? say:
100
/ \
50 20
/ \ \
30 40 26
Some comments:
You definitely don’t need the while loop – you always return after the first iteration
2i + 1doesn’t work in java, you need to use2*i + 1arr[2*i + 1]andarr[2*i + 1]may throw andArrayIndexOutOfBoundsExceptionso you need to either manually do a range check, or wrap it in atry.. catchblock