Wednesday, December 3, 2008

Non recursive insert operation in binary tree.

struct Node{
Node* Left;
Node* Right;
int Val;
};
void InsertNodeNonRecursive(Node** ppNode, int val)
{
if(ppNode == NULL)
return;
if(*ppNode == NULL)
{
*ppNode = new Node();
(*ppNode)->Val = val;
(*ppNode)->Left = (*ppNode)->Right = NULL;
}
else
{
Node *pNode = *ppNode;
Node *pParent = NULL;
while(pNode != NULL)
{
//need to store the parent as we hit the NULL using pNode
pParent = pNode;
if( val > pNode->Val)
pNode = pNode->Right;
else
pNode = pNode->Left;
}
if(val > pParent->Val)
{
pParent->Right = new Node();
pParent->Right->Val = val;
pParent->Right->Left = NULL;
pParent->Right->Right = NULL;
}
else
{
pParent->Left = new Node();
pParent->Left->Val = val;
pParent->Left->Left = pParent->Left->Right = NULL;
}
}

}
int _tmain(int argc, _TCHAR* argv[])
{
Node* Head1 = NULL;
InsertNodeNonRecursive(&Head1,6);
InsertNodeNonRecursive(&Head1,4);
InsertNodeNonRecursive(&Head1,5);
InsertNodeNonRecursive(&Head1,2);
InsertNodeNonRecursive(&Head1,3);
InsertNodeNonRecursive(&Head1,1);
InsertNodeNonRecursive(&Head1,8);
InsertNodeNonRecursive(&Head1,7);
InsertNodeNonRecursive(&Head1,9);
return 0;
}

No comments: