I am building a Heap data structure, but the part that is driving me nuts is checking for a null child value.
I am using a Vector, and I am comparing a parent against a child, but if there’s only one child the program crashes since something like
vectorObject.get(i) //i'th element doesn't exist
will return an exception.
I can’t check for the null element with something like
if (vectorObject.get(i) == null)
since running the get() method will automatically break the program, so how do you ACTUALLY check for a non-existing element without some unreadable weird hack-around??
You seem very confused. I think you need to re-read whatever reference you’re using to design your heap data structure (or read the relevant section of the Wikipedia article).
If your parent is at
0then your children are at2*(0)+1=1and2*(0)+2=2. In this case,1 < vectorObject.size()will be true but2 < vectorObject.size()is false, meaning there is a left child but no right child.Since the
Vector(orArrayListif you’ve switched as per my suggestion) is zero-based you need to check ifi < vectorObject.size(), noti <= vectorObject.size(). Ifi < vectorObject.size()theniis a legal index.Update:
There are two ways you can structure the logic here. If you have to handle the single-child case totally differently than the two-child case then this would probably work best:
If you handle the two nodes separately, then nesting might be better: