Insertion in Binary search tree by R4R Team

How insert data in Binary search Tree ?
When we have data to insert in BST then start with the root then compare both value, if it is less then root value then goes to left subtree and repeat process until we reach leaf node else goes to right subtree and repeat the process.

Following is the function which are used to insert the element in BST(Binary search Tree).

void insert(int data)
{
struct node *tempNode=(struct node*)malloc(sizeof(struct node));
struct node *current;
struct node *parent;
tempNode->data=data;
tempNode->leftchild=NULL;
tempNode->rightchild=NULL;
if(root==NULL)
{
root=tempNode;
}
else
{
current=root;
parent=NULL;
while(1)
{
parent=current;
if(data< parent->data){
current=current->leftchild;
if(current==NULL)
{
parent->leftchild=tempNode;
return;
}
}
else
{
current=current->rightchild;
if(current==NULL)
{
parent->rightchild=tempNode;
return;
}
}
}
}
}




Leave a Comment:
Search
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!