BINARY SEARCH TREE IN C

#include<stdio.h>
#include<string.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *insert(struct node *root,int data)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=data;
newnode->left=NULL;
newnode->right=NULL;
if(root==NULL)
{
root=newnode;
}
else if(root->data>data)
{
root->left=insert(root->left,data);
}
else
{
root->right=insert(root->right,data);
}
return root;
}
void in(struct node *root)
{
if(root!=NULL)
{
in(root->left);
printf(" %d ",root->data);
in(root->right);
}
}

void in1(struct node *root)
{
if(root!=NULL)
{
in(root->left);
printf(" %d ",root->data);
}
}
void in2(struct node *root)
{
if(root!=NULL)
{
printf(" %d ",root->data);
in(root->right);
}
}
main()
{
struct node *root=NULL;
root=insert(root,15);
root=insert(root,10);
root=insert(root,20);
root=insert(root,8);
root=insert(root,12);
root=insert(root,16);
root=insert(root,25);
in(root);
puts("");
in1(root);
puts("");
in2(root);
}

Comments

Popular posts from this blog

How whatsapp works

Android N Developer Preview? It's exciting for most of you