Thursday 19 August 2010

C program to implement expression tree

#include
#include
#include

typedef struct tree
{
char data;
struct tree *left;
struct tree *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 preorder(pos t)
{
if(t!=NULL)
{
printf(“%c”,t->data);
preorder(t->left);
preorder(t->right);
}
}
void postorder(pos t)
{
if(t!=NULL)
{
postorder(t->left);
postorder(t->right);
printf(“%c”,t->data);
}
}
void main()
{
char a[30];
pos temp, t;
int i ,j;
clrscr();
printf(“\t\t Expression tree”);
printf(“\nEnter the postfix expression:”);
gets(a);
for(i=0;a[i]!=NULL;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 Inorder Traversal”);
inorder(temp);
printf(“\n Preorder Traversal”);
preorder(temp);
printf(“\n postorder Traversal”);
postorder(temp);
getch();}


OUTPUT:


Enter the expression in postfix form : ab+c-

Inorder traversal : a+b-c

Preorder traversal : -+abc

Postorder traversal : ab+c-

No comments:

Post a Comment