#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
int count=1;
struct node
{
int data;
struct node* LEFT;
struct node* RIGHT;
};
struct node* insert(struct node* root,int value)
{
if(root==NULL)
{
root=(struct node*)malloc(sizeof(struct node));
root->data=value;
root->LEFT=root->RIGHT=NULL;
count++;
}
else if(count%2==0)
{
root->LEFT=insert(root->LEFT,value);
}
else
{
root->RIGHT=insert(root->RIGHT,value);
}
return root;
}
void inorder(struct node* root)
{
if(root!=NULL)
{
inorder(root->LEFT);
printf("%d ",root->data);
inorder(root->RIGHT);
}
}
void postorder(struct node* root)
{
if(root!=NULL)
{
postorder(root->LEFT);
postorder(root->RIGHT);
printf("%d ",root->data);
}
}
void preorder(struct node* root)
{
if(root!=NULL)
{
printf("%d ",root->data);
preorder(root->LEFT);
preorder(root->RIGHT);
}
}
int height(struct node* root)
{
int r,l;
if(root==NULL)
{
return -1;
}
else
{
l=height(root->LEFT);
r=height(root->RIGHT);
if(l>r)
{
return l+1;
}
else
{
return r+1;
}
}
}
void printlevelorder(struct node* root,int level)
{
if(root==NULL)
{
return;
}
else
{
if(level==1)
{
printf("%d ",root->data);
}
else if(level>1)
{
printlevelorder(root->LEFT,level-1);
printlevelorder(root->RIGHT,level-1);
}
}
}
void levelorder(struct node* root)
{
int h,i;
h=height(root);
for(i=1;i<=h+1;i++)
{
printlevelorder(root,i);
}
}
void main()
{
int ch;
struct node* root=NULL;
while(1)
{
printf("\nPlease enter your choice\n1. Insert\n2. Display inorder\n3. Display postorder\n4. Display Preorder\n5. Height\n6. Display levelorder \n\nChoice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
int temp;
printf("Enter the data to insert: ");
scanf("%d",&temp);
root=insert(root,temp);
break;
}
case 2:
{
inorder(root);
break;
}
case 3:
{
postorder(root);
break;
}
case 4:
{
preorder(root);
break;
}
case 5:
{
printf("HEIGHT= %d",height(root));
break;
}
case 6:
{
levelorder(root);
break;
}
default:
exit(0);
}
}
}
0 Comments