# Thread: deleting arbitrary node from a heap

1. ## deleting arbitrary node from a heap

So I have a heap structure that I coded up, and it works well. My friend and I are working on a project together that uses this heap structure, and he informed me that we need a function that allows us to delete an arbitrary node from the heap instead of just the max node.

So I went to code one up....

I just wanted to make sure I have my logic correct though before I actually try and use this function. My logic is this:

When we normally delete the max node from the heap (it's a max heap), we just take the node at the end of the array and move it up into the 0th spot. Then we heapify it.

I figured, why not do that for any arbitrary node? The last node in the array is guaranteed to be a leaf node, so to delete any arbitrary node in the heap, do you think I could just move the last node in the array up to the index of the arbitrary node we are deleting, and the call heapify to restructure the heap and make sure it is good?

Here is my code itself:

Code:
```node* heap_extractNode(heap* myHeap, node *myNode)
{
int i;
node *nodeFound;

//Make sure the heap is not empty.  If it is empty, return NULL
if ( heap_isEmpty(myHeap) )
return NULL;

//Search for the node in the heap
for ( i = 0; i < myHeap->size; i++ )
{
if ( myHeap->nodes[i]->priority == myNode->priority &&
{
nodeFound = myHeap->nodes[i];
myHeap->nodes[i] = myHeap->nodes[myHeap->size - 1];
}
}

myHeap->size = myHeap->size - 1;

heap_heapify ( myHeap, 0 );

return nodeFound;
}```

2. Maybe you should start the heapify process at i instead of at 0? (I'm assuming your heapify assumes a mostly-heap; if not, then never mind.)

3. Well certainly starting it at i instead of 0 would be more efficient

That doesn't really matter to me though. I just wanted to know if my logic is sound, and that I am not completely screwing up the heap by deleting nodes in this manner.

4. Since you know that > is transitive, you know that a node is not just greater than it's children, but all its descendants. As long as you had a heap in the first place, moving a node halfway up and then heapifying can't hurt anything.

5. Originally Posted by DavidP
Well certainly starting it at i instead of 0 would be more efficient

That doesn't really matter to me though. I just wanted to know if my logic is sound, and that I am not completely screwing up the heap by deleting nodes in this manner.
Then you can rest assured that yes, that is how removal of an arbitrary node from a heap should be done.