Page 137 - DCAP605_ADVANCED_DATA_STRUCTURE_AND_ALGORITHMS
P. 137
Advanced Data Structure and Algorithms
Notes }
}
}
}
/* A function to insert a new node in binary search tree to get a tree
created*/
struct tnode *insert(struct tnode *p,int val)
{
struct tnode *temp1,*temp2;
if(p == NULL)
{
p = (struct tnode *) malloc(sizeof(struct tnode)); /* insert the new
node as root node*/
if(p == NULL)
{
printf(“Cannot allocate\n”);
exit(0);
}
p->data = val;
p->lchild=p->rchild=NULL;
}
else
{
temp1 = p;
/* traverse the tree to get a pointer to that node whose child will be
the newly created node*/
while(temp1 != NULL)
{
temp2 = temp1;
if( temp1 ->data > val)
temp1 = temp1->lchild;
else
temp1 = temp1->rchild;
}
if( temp2->data > val)
{
temp2->lchild = (struct tnode*)malloc(sizeof(struct tnode));/ *inserts
the newly created node
as left child*/
temp2 = temp2->lchild;
if(temp2 == NULL)
{
printf(“Cannot allocate\n”);
132 LOVELY PROFESSIONAL UNIVERSITY