Professional Documents
Culture Documents
struct node
{
int info;
struct node *llink;
struct node *rlink;
};
typedef struct node *NODE;
NODE root = NULL;
// Function to insert nodes in to the tree
NODE insert(NODE root)
{
NODE temp,cur,prev;
int item;
printf("enter the value n");
scanf("%d",&item);
temp=(NODE) malloc(sizeof(NODE));
if(temp ==NULL)
{
printf("out of memory \n");
exit(0);
}
temp->info=item;
temp->llink=NULL;
temp->rlink=NULL;
if(root==NULL)
{
root=temp;
printf("%d is inserted\n",temp ->info);
return root;
}
prev=NULL;
cur=root;
while(cur!=NULL)
{
prev=cur;
if(item<cur->info)
cur=cur->llink;
else
cur=cur->rlink;
}
if(item < prev->info)
{
prev->llink=temp;
printf("%d is inserted as left child of %d\n",
temp->info, prev->info);
}
else
{
prev->rlink=temp;
printf("%d is inserted as right child of %d\n",
temp >info,prev->info);
}
return root;
}
// Function to find the pre-order traversal of the tree
void preorder(NODE root)
{
if(root==NULL)
return;
printf("%d\t",root->info);
preorder(root->llink);
preorder(root->rlink);
}
// Function to find the in-order traversal of the tree
void inorder(NODE root)
{
if(root==NULL)
return;
inorder(root->llink);
printf("%d\t",root->info);
inorder(root->rlink);
}
// Function to find the post-order traversal of the tree
void postorder(NODE root)
{
if(root==NULL)
return;
postorder(root->llink);
postorder(root->rlink);
printf("%d\t",root->info);
}
// Function to find the smallest element of the tree
NODE findSmallestElement(NODE root)
{
if ((root == NULL) || (root->llink == NULL))
return root;
else
return findSmallestElement(root ->llink);
}
// Function to find the largest element of the tree
NODE findLargestElement(NODE root)
{
if( (root == NULL) || (root->rlink == NULL))
return root;
else
return findLargestElement(root->rlink);
}
// Function to find the total number of nodes of the tree
int totalNodes(NODE root)
{
if(root==NULL)
return 0;
else
return(totalNodes(root–>llink) + totalNodes(root–>rlink) + 1);
}