Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively check if an array represents a heap

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
like image 607
Hank Avatar asked Oct 29 '25 18:10

Hank


1 Answers

Some comments:

  • You definitely don't need the while loop - you always return after the first iteration

  • 2i + 1 doesn't work in java, you need to use 2*i + 1

  • arr[2*i + 1] and arr[2*i + 1] may throw and ArrayIndexOutOfBoundsException so you need to either manually do a range check, or wrap it in a try.. catch block

like image 96
Denis Tulskiy Avatar answered Nov 01 '25 09:11

Denis Tulskiy