Original Post
So I've been banging my head on a quick way to implement insert for a binary heap data structure built with a binary tree. The problem comes in finding the best possible insertion point to then peculate the node up into its position. Heres the algorithm i'm running now for insert which is way to slow. And here is what the recursive call looks like The time to move the node into place is really fast, but I'd like to move my insertion speed to more of a rate of O(1) instead of 0(n) like it is now. So my question is does anyone know of a way I can improve this? Or is there a better way to perform insertion when using a binary tree for holding the data instead of an array? Thanks Adam
//! Insert a new item into the heap
void Insert( T data )
{
Leaf<T>* pNewNode = GetNewLeaf( data );
Leaf< T >* pBestParent = NULL;
if( m_pRoot == NULL )
{
m_pRoot = pNewNode;
}
else
{
int nDepth = 0;
pBestParent = GetPositionInTree( m_pRoot, nDepth );
//See which side to insert the node on
if( pBestParent->m_pLeft == NULL )
pBestParent->m_pLeft = pNewNode;
else
pBestParent->m_pRight = pNewNode;
pNewNode->m_pParent = pBestParent;
printf( "Depth = %d \n", nDepth );
}
//Now time to heapify
if( pBestParent != NULL )
HeapifyUp( pBestParent );
}
//! Helper returns the best parent for this new node
Leaf< T >* GetPositionInTree( Leaf< T >* pLeaf, int& nDepth )
{
//Simple check if there is a left and right keep recurring
if( pLeaf->m_pLeft != NULL && pLeaf->m_pRight != NULL )
{
nDepth++;
int nLeftDepth = nDepth;
int nRightDepth = nDepth;
Leaf< T >* pBestLeft = GetPositionInTree( pLeaf->m_pLeft, nLeftDepth );
Leaf< T >* pBestRight = GetPositionInTree( pLeaf->m_pRight, nRightDepth );
if( nLeftDepth > nRightDepth )
{
nDepth = nRightDepth;
return pBestRight;
}
else
{
nDepth = nLeftDepth;
return pBestLeft;
}
}
//No children this is the best parent
return pLeaf;
}