Thursday, July 30, 2009

Creating a binary search tree using c code?

i want program to create and insert an element in a binary search tree using c language

Creating a binary search tree using c code?
use pointers, struct, etc





struct node{


node * child1,child2;// child1 == left n child2 == right


int value;


};





void insert( node * insertnode, node * insertingnode){


if ( insertingnode-%26gt; value %26gt; insertnode -%26gt; value ){





if( insertingnode -%26gt; child1 != NULL )


insetingnode -%26gt; insetnode;


else// use recursion


insert( insetnode, insetingnode -%26gt; child1 );





}


else {





if( insertingnode -%26gt; child2 != NULL )


insetingnode -%26gt; insetnode;


else// use recursion


insert( insetnode, insetingnode -%26gt; child2 );





}





}
Reply:struct btree


{


struct btree *left;


struct btree *right;


struct info;


};/*structure for representing a node in btree*/


struct btree *root=NULL;


/* function to create root level node being called by main */


void create(int n)


{


struct btree *temp;


temp=(struct btree *)(malloc(sizeof(struct btree));


temp-%26gt;info=n;


if(root==NULL)


root=temp;


else


printf("tree already constructed");


}


/call insert in main by sending address of root %26amp; value n*/


void insert(struct btree **r,int n)


{


if((*r)==NULL)


{


(*r)=(struct btree *)malloc(sizeof(struct btree));


(*r)-%26gt;left=(*r)-%26gt;right=NULL;


(*r)-%26gt;info=n);


return;


}


if((*r)-%26gt;info%26gt;n))


insert(%26amp;(*r)-%26gt;left,n);


else


insert(%26amp;(*r)-%26gt;right,n);


}


No comments:

Post a Comment