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;
}
}
}
}
}