0

I am trying to find the smallest value in a max heap(stored in an array) recursively, without reversing the array. I have some problems trying to define the recursive case. How do I give the correct index to the recursive call? (starting index from 1 instead of 0)If the first node is stored in slot i, then I know that its left and right nodes are stored in slot 2*i and 2*i+1 respectively and so are their own left and right nodes. How do I pass this information recursively?

pseudo-code:

smallest(size ,index_of_parent_node){
   i = size/2
   if (i == 0)
      return A[i]
   else 
      return min[smallest(size/2 , index_of_left_of_parent) , smallest(size/2, index_of_right_of_parent)]
  • 5
    I don't think you can do it, min for sure is stored on the bottom layer of max heap, but without additional properties of your heap you can't guarantee anything else, so search anyway will take `O(heapSize)` – fas Apr 02 '20 at 05:31
  • One of the leaves will have the min value. – nice_dev Apr 02 '20 at 06:29
  • 1
    Searching a binary heap recursively is silly. Since you know that the smallest node will be a leaf, and that the leaves make up half the nodes in the heap, the easiest way to find the smallest node in a max-heap is to start at `A[size/2]` and search linearly to the end. – Jim Mischel Apr 02 '20 at 17:10

1 Answers1

1

I have some problems trying to define the recursive case. How do I give the correct index to the recursive call? (starting index from 1 instead of 0)If the first node is stored in slot i, then I know that its left and right nodes are stored in slot 2*i and 2*i+1 respectively and so are their own left and right nodes. How do I pass this information recursively?

The current implementation does not work because it will not look at all the leaf nodes. The minimum element will be one of the leaf nodes.

If you want to do it recursively then you can start from the root node of the max-heap and get the minimum from its two subtrees recursively like below -

def getSmallestNumber (maxHeapArray , size):
    #assuming maxHeapArray has at least one element
    #and 1-based indexing
    return helper(maxHeapArray, size, 1)

def helper (maxHeapArray, size, currentIndex):
    if currentIndex >= size:
       return maxHeapArray[currentIndex]

    currentNumber = maxHeapArray[currentIndex]
    leftIndex     = 2 * currentIndex   
    rightIndex    = 2 * currentIndex + 1
    leftMin       = helper(maxHeapArray, size, leftIndex)
    rightMin      = helper(maxHeapArray, size, rightIndex)
    return min(currentNumber, leftMin, rightMin)

You can also do a linear traversal of the complete array or half of the elements. Time complexity to get min elements from max-heap

Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
valarMorghulis
  • 302
  • 1
  • 12