0

Bellow is the method I'm confused by. Why do k, right, and left need to be greater than n?

// is subtree of pq[1..n] rooted at k a min heap?
    private boolean isMinHeap(int k) {
        if (k > n) return true;
        int left = 2*k;
        int right = 2*k + 1;
        if (left  <= n && greater(k, left))  return false;
        if (right <= n && greater(k, right)) return false;
        return isMinHeap(left) && isMinHeap(right);
    }
Shalbert
  • 1,044
  • 11
  • 17
  • A binary heap is a complete binary tree which satisfies the heap ordering property. The ordering can be one of two types: the min-heap property: the value of each node is greater than or equal to the value of its parent, with the minimum-value element at the root. [https://www.cs.cmu.edu/~adamchik/15-121/lectures/Binary%20Heaps/heaps.html](https://www.cs.cmu.edu/~adamchik/15-121/lectures/Binary%20Heaps/heaps.html) – R.Laney Mar 08 '18 at 18:02

1 Answers1

0

The reason for the length check is to ensure that you don't try to access an element off the end of the array. You have this code:

    if (k > n) return true;
    int left = 2*k;
    int right = 2*k + 1;
    if (left  <= n && greater(k, left))  return false;
    if (right <= n && greater(k, right)) return false;

Remember, k, left, and right are indexes to the backing array. They aren't actual values. So if (k > n) isn't comparing the node's value to the array length, it's making sure that the index is within the array bounds.

What greater(k, left) does is, essentially:

return a[left] > a[k];

Let's say that k is the index of a leaf node. Then left will be an index that's beyond the end of the array, and greater will try to access an element that doesn't exist in the heap. To prevent that, the code makes sure that left <= n.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351