Search code examples
c++treeheapchildren

parent in a heap has children or not


I am trying to check a Max-Heap to see whether a parent has children or not. My heap is implemented as a vector. At first i wrote a function bool hasChildren(int loc) loc is the location of the parent in the heap. my main conditional was:

if(heap[2*loc + 1] == NULL && heap[2*loc + 2] == NULL)   //if there are children

The problem is that you cannot check out of bounds indices... I thought of pointer arithmetic but that is invalid too. Does anybody have a suggestion for how to check whether a parent in a heap has children?

thanks!


Solution

  • The problem is that you cannot check out of bounds indices

    If this is an std::vector, you can use its at member function and catch the std::out_of_range exception.