我们如何检查一个数组是否递归地表示一个堆数据结构?假设它是一个整数数组,我正在检查最大堆。以下是我想出的,但我不知道这是否正确。
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