Search This Blog

Tuesday 27 October 2015

Construction of Expression tree using postfix expression

#include<stdio.h>
#include<conio.h>

typedef struct tree
{
char data;
struct tree *left, *right;
}*pos;
pos stack[30];
int top=-1;
pos newnode(char b)
{
pos temp;
temp= (struct tree*)malloc(sizeof(struct tree));
temp->data=b;
temp->left=NULL;
temp->right=NULL;
return temp;
}
void push(pos temp)
{
stack[++top]=temp;
}
pos pop()
{
pos p;
p=stack[top--];
return p;
}
void inorder(pos t)
{
if(t!=NULL)
{
inorder(t->left);
printf("%c",t->data);
inorder(t->right);
}
}
void postorder(pos t)
{
if(t!=NULL)
{
postorder(t->left);
postorder(t->right);
printf("%c",t->data);
}
}
void preorder(pos t)
{
if(t!=NULL)
{
printf("%c",t->data);
preorder(t->left);
preorder(t->right);
}
}

void main()
{
char a[20];
pos temp, t;
int i,j;
clrscr();
printf("\nEnter postfix expression : ");
scanf("%s",a);
for(i=0;a[i]!='\0';i++)
{
if(a[i]=='*'||a[i]=='/'||a[i]=='+'||a[i]=='-')
{
temp=newnode(a[i]);
temp->right=pop();
temp->left=pop();
push(temp);
}
else
{
temp=newnode(a[i]);
push(temp);
}
}
printf("\n\nINORDER TRAVERSAL  ");
inorder(temp);
printf("\n\nPREORDER TRAVERSAL  ");
preorder(temp);
printf("\n\nPOSTORDER TRAVERSAL  ");
postorder(temp);
getch();
}

No comments:

Post a Comment