Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

TO CONSTRUCT AN EXPRESSION TREE FROM A GIVEN POSTFIX

EXPRESSION.

#include <stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct node{
char data;
struct node *left;
struct node *right;
};
struct node *st[100];
int top=-1;
void display();
void push(struct node *temp );
void inorder(struct node *tree);
void preorder(struct node *tree);
void postorder(struct node *tree);
struct node * pop();
void main()
{
int i;
char exp[100];
printf("enter an postfix expression ");
gets(exp);
while(exp[i]!='\0')
{
struct node *temp;
struct node *t1;
struct node *t2;
temp->data=exp[i];
switch(exp[i])
{
case '+':
case '-':
case '*':
case '/':
t2=pop();
t1=pop();
temp->right=t2;
temp->left=t1;
push(temp);
break;
default:
temp->left=NULL;
temp->right=NULL;
push(temp);
break;
}}
display();
}
void push(struct node *temp)
{
if(top==99)
printf("Cannot push");
else
st[++top]=temp;
}
struct node * pop()
{ struct node *temp;
if (top==-1)
printf ("cannot pop");
else
temp=st[top--];
return temp;
}
void display()
{
preorder(st[top]);
postorder(st[top]);
inorder(st[top]);
}
void preorder(struct node * tree)
{
if(tree!=NULL)
{
printf("%c",tree->data);
preorder(tree->left);
preorder(tree->right);
}
}
void inorder(struct node * tree)
{
if(tree!=NULL)
{
preorder(tree->left);
printf("%c",tree->data);
preorder(tree->right);
}
void postorder(struct node * tree)
{
if(tree!=NULL)
{
preorder(tree->left);
preorder(tree->right);
printf("%c",tree->data);
}
}

You might also like