typedef struct bst
{
int data;
struct bst *left,*right; // Left and Right child of a tree.
}node;
node* get_node(); // To initialize the tree(allocating memory).
Void insert(node*,node*); //To insert a node in the tree
void main()
{
int ans;
printf("\nEnter Elements 1 by 1: (0 to stop entering)\n");
do
{
New=get_node(); // allocating memory
scanf("%d",&New->data);
ans=New->data;
if(ans!=0)
if(root==NULL)
root=New;
else
insert(root,New);
}while(ans!=0);
}
/*Get node*/
node *get_node()
{
node *temp;
temp=(node *)malloc(sizeof(node));
temp->left=NULL;
temp->right=NULL;
return temp;
}
/*Insert Function*/
void insert(node *root,node *New)
{
if(New->data < root->data)
{
if(root->left==NULL)
root->left=New;
else
insert(root->left,New);
}
if(New->data > root->data)
{
if(root->right==NULL)
root->right=New;
else
insert(root->right,New);
}
}
No comments:
Post a Comment