/* trees */
# include
# include
struct node
{ struct node *left;
int num;
struct node *right;
};
main()
{
int ch,num;
struct node *start=NULL;
while(1)
{
clrscr();
printf("\n\t\tMain Menu");
printf("\n\t\t1. Insert into tree");
printf("\n\t\t2. Display tree in preorder fashion");
printf("\n\t\t3. Display tree in inorder fashion");
printf("\n\t\t4. Display tree in postorder fashion");
printf("\n\t\t5. Exit program");
printf("\n\t\Enter your choice(1-5)");
scanf("%d",&ch);
switch(ch)
{ case 1:
printf("\nEnter number to be inserted");
scanf("%d",&num);
insnode(&start,num);
break;
case 2:
preorder(start);
break;
case 3:
inorder(start);
break;
case 4:
postorder(start);
break;
case 5:
return;
default:
printf("\nWrong choice");
}
getch();
}
}
insnode(struct node *p, int n)
{
if(p==NULL)
{
p=(struct node *) malloc(sizeof(struct node));
p->num=n;
p->left=NULL;
p->right=NULL;
}
else
{
if(n>(p->num))
insnode(p->right,n);
else
insnode(p->left,n);
}
}
preorder(struct node *p)
{
if(p==NULL)
return;
else
{
printf("\nNode:%d",p->num);
preorder(p->left);
preorder(p->right);
}
}
inorder(struct node *p)
{
if(p==NULL)
return;
else
{
inorder(p->left);
printf("\nNode:%d",p->num);
inorder(p->right);
}
}
postorder(struct node *p)
{
if(p==NULL)
return;
else
{
postorder(p->left);
postorder(p->right);
printf("\nNode:%d",p->num);
}
}
# include
# include
struct node
{ struct node *left;
int num;
struct node *right;
};
main()
{
int ch,num;
struct node *start=NULL;
while(1)
{
clrscr();
printf("\n\t\tMain Menu");
printf("\n\t\t1. Insert into tree");
printf("\n\t\t2. Display tree in preorder fashion");
printf("\n\t\t3. Display tree in inorder fashion");
printf("\n\t\t4. Display tree in postorder fashion");
printf("\n\t\t5. Exit program");
printf("\n\t\Enter your choice(1-5)");
scanf("%d",&ch);
switch(ch)
{ case 1:
printf("\nEnter number to be inserted");
scanf("%d",&num);
insnode(&start,num);
break;
case 2:
preorder(start);
break;
case 3:
inorder(start);
break;
case 4:
postorder(start);
break;
case 5:
return;
default:
printf("\nWrong choice");
}
getch();
}
}
insnode(struct node *p, int n)
{
if(p==NULL)
{
p=(struct node *) malloc(sizeof(struct node));
p->num=n;
p->left=NULL;
p->right=NULL;
}
else
{
if(n>(p->num))
insnode(p->right,n);
else
insnode(p->left,n);
}
}
preorder(struct node *p)
{
if(p==NULL)
return;
else
{
printf("\nNode:%d",p->num);
preorder(p->left);
preorder(p->right);
}
}
inorder(struct node *p)
{
if(p==NULL)
return;
else
{
inorder(p->left);
printf("\nNode:%d",p->num);
inorder(p->right);
}
}
postorder(struct node *p)
{
if(p==NULL)
return;
else
{
postorder(p->left);
postorder(p->right);
printf("\nNode:%d",p->num);
}
}
No comments:
Post a Comment