/*Tree (Recursive – inorder , preorder , postorder)*/
#include<stdio.h>
#include<conio.h>
typedef struct tree{
struct tree *right;
struct tree *left;
int data;
}node;
void inorder(node *root)
{
if(root!=NULL)
{
inorder(root->left);
printf("%d ",root->data);
inorder(root->right);
}
}
void preorder(node *root)
{
if(root!=NULL)
{
printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}
}
void postorder(node *root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d ",root->data);
}
}
node *getnode()
{
int val;
node *temp;
printf("\nEnter data:");
scanf("%d",&val);
temp=(node *)malloc(sizeof(node));
temp->data=val;
temp->right=NULL;
temp->left=NULL;
return temp;
}
node *insert(node *root)
{
char ch;
node *neww;
if(root==NULL)
{
neww=getnode();
root=neww;
}
printf("\n\Ok now next node where to add?(L/R):");
scanf("\n%c",&ch);
if(ch=='l' || ch=='L')
{
neww=getnode();
if(root->left==NULL)
{
root->left=neww;
}
else
{
insert(root->left);
}
}
else if(ch=='r' || ch=='R')
{
neww=getnode();
if(root->right==NULL)
{
root->right=neww;
}
else
{
insert(root->right);
}
}
else
{
printf("\nEnter proper choice");
}
return root;
}
void main()
{
int ch;
node *s=NULL;
clrscr();
while(1)
{
printf("\n1.insert\n2.inorder\n3.preorder\n4.postorder\n5.exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1:s=insert(s);
break;
case 2:inorder(s);
break;
case 3:preorder(s);
break;
case 4:postorder(s);
break;
case 5:exit(0);
break;
default:printf("\nEnter proper choice\n");
}
}
}
#include<stdio.h>
#include<conio.h>
typedef struct tree{
struct tree *right;
struct tree *left;
int data;
}node;
void inorder(node *root)
{
if(root!=NULL)
{
inorder(root->left);
printf("%d ",root->data);
inorder(root->right);
}
}
void preorder(node *root)
{
if(root!=NULL)
{
printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}
}
void postorder(node *root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d ",root->data);
}
}
node *getnode()
{
int val;
node *temp;
printf("\nEnter data:");
scanf("%d",&val);
temp=(node *)malloc(sizeof(node));
temp->data=val;
temp->right=NULL;
temp->left=NULL;
return temp;
}
node *insert(node *root)
{
char ch;
node *neww;
if(root==NULL)
{
neww=getnode();
root=neww;
}
printf("\n\Ok now next node where to add?(L/R):");
scanf("\n%c",&ch);
if(ch=='l' || ch=='L')
{
neww=getnode();
if(root->left==NULL)
{
root->left=neww;
}
else
{
insert(root->left);
}
}
else if(ch=='r' || ch=='R')
{
neww=getnode();
if(root->right==NULL)
{
root->right=neww;
}
else
{
insert(root->right);
}
}
else
{
printf("\nEnter proper choice");
}
return root;
}
void main()
{
int ch;
node *s=NULL;
clrscr();
while(1)
{
printf("\n1.insert\n2.inorder\n3.preorder\n4.postorder\n5.exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1:s=insert(s);
break;
case 2:inorder(s);
break;
case 3:preorder(s);
break;
case 4:postorder(s);
break;
case 5:exit(0);
break;
default:printf("\nEnter proper choice\n");
}
}
}
No comments:
Post a Comment