0
708views
Write a menu-driven C Program to construct an expression tree in preorder and inorder format using postorder expression.

Test program for the following Post-order Expressions:

1] AB+

2] AB+CD-*

3] ABC+*C*

4] AB+C*D-

1 Answer
0
4views

Menu-driven C Program to construct Inorder, Preorder expression from Postorder Expression

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
typedef struct treenode
{
char data;
struct treenode *left,*right;
}treenode;
typedef struct stack
{
treenode *data[20];
int top;
}stack;
void init(stack *s)
{
s->top=-1;
}
treenode *pop(stack *s)
{
treenode *p;
p=s->data[s->top];
s->top=s->top-1;
return(p);
}
void push(stack *s,treenode *p)
{
s->top=s->top+1;
s->data[s->top]=p;
}
int empty(stack *s)
{
if(s->top==-1)
return(1);
return(0);
}
int full(stack *s)
{
if(s->top==19)
return(1);
return(0);
}
treenode *create();
void inorder(treenode *T);
void preorder(treenode *T);
void postorder(treenode *T);
void main()
{
treenode *root=NULL,*p;
int x,op;

do
{
printf("\n\n1.Create\n2.Pre-order\n3.In-order\n4.Post-order\n5.Quit");
printf("\n Enter Your Choice: ");
scanf("%d",&op);
switch(op)
{
case 1:root=create();
       break;
case 2:printf("Pre-order Expression: ");
       preorder(root);
       break;
case 3:printf("In-order Expression: ");
       inorder(root);
       break;
case 4:printf("Post-order Expression: ");
       postorder(root);
       break;
}
}while(op!=5);
getch();
}
void inorder(treenode *T)
{
if(T!=NULL)
{
inorder(T->left);
printf("%c",T->data);
inorder(T->right);
}
}
void preorder(treenode *T)
{
if(T!=NULL)
{
printf("%c",T->data);
preorder(T->left);
preorder(T->right);
}
}
void postorder(treenode *T)
{
if(T!=NULL)
{
postorder(T->left);
postorder(T->right);
printf("%c",T->data);
}
}
treenode * create()
{
char a[50];
int i;
treenode *p,*q,*root;
stack s;
init(&s);
printf("\n Enter Postfix Eexpression: ");
scanf("%s",a);
for(i=0;a[i]!='\0';i++)
{
 if(isalnum(a[i]))
 {
 p=(treenode *)malloc(sizeof(treenode));
 p->left=p->right=NULL;
 p->data=a[i];
 push(&s,p);
 }
 else
 {
 q=pop(&s);
 p=pop(&s);
 root=(treenode *)malloc(sizeof(treenode));
 root->left=p;
 root->right=q;
 root->data=a[i];
 push(&s,root);
 }
 }
 root=pop(&s);
 return(root);
 }

OUTPUT -

1] Test case for Post-order Expression AB+

AB+

2] Test case for Post-order Expression AB+CD-*

AB+CD-*

3] Test case for Post-order Expression ABC+*C*

ABC+<em>C</em>

4] Test case for Post-order Expression AB+C*D-

AB+C*D-

Please log in to add an answer.