Top baner Big

Your Ad Here

Top Banner

Your Ad Here

Saturday, November 22, 2008

Expression Tree

/*Program : Expression Tree
Programmer ::fizmhd(MEA) www.mdown.co.cc*/




#include

struct tree
{
char info;
struct tree *rchild;
struct tree *lchild;
};

int prec(char data);

typedef struct tree * node;

char pop_op();
node pop_num();
void push_op(char item);

node create()
{
return((node)malloc(sizeof(node)));
}
node num[20],root=NULL;
char op[20],oprt,ev[20];
int nt=-1,ot=-1,et=-1;


main()
{
node newnode,item,temp;
char str[50];
int i,k,p,s,flag=0;
printf("ENTER THE EXPRESSION ");
scanf("%s",str);
printf("\n%s",str);
for(i=0;str[i]!='\0';i++)
{
if(isalnum(str[i]))
{
newnode=create();
newnode->info=str[i];
newnode->lchild=NULL;
newnode->rchild=NULL;
item=newnode;
push_num(item);
}
else
{
if(ot!=-1)
p=prec(op[ot]);
else
p=0;
k=prec(str[i]);
if(k==5)
{
while(k!=1)
{
oprt=pop_op();
newnode=create();
newnode->info=oprt;
newnode->rchild=pop_num();
newnode->lchild=pop_num();
// if(root==NULL)
root=newnode;
// else if((newnode->rchild==root)||(newnode->lchild==root))
// root=newnode;
push_num(root);
k=prec(op[ot]);
}
oprt=pop_op();
}
else if(k==1)
push_op(str[i]);
else
{
if(k>p)
push_op(str[i]);
else
{
if(k<=p)
{
oprt=pop_op();
newnode=create();
newnode->rchild=pop_num();
newnode->lchild=pop_num();
if(root==NULL)
root=newnode;
else if((newnode->rchild==root)||(newnode->lchild==root))
root=newnode;
push_num(newnode);
push_op(str[i]);
// k=prec(op[ot]);
}
}
}
}
}
printf("\nThe prefix expression is\n ");
preorder(root);
printf("\nThe infix exp is\n ");
inorder(root);
printf("\nThe postfix expression is\n ");
postorder(root);
evaluate();
}
void push_op(char item)
{
op[++ot]=item;
}
push_num(node item)
{
num[++nt]=item;
}
char pop_op()
{
if(ot!=-1)
return(op[ot--]);
else
return(0);
}
node pop_num()
{
if(nt!=-1)
return(num[nt--]);
else
return(NULL);
}
int prec(char data)
{
switch(data)
{
case '(':return(1);
break;
case '+':
case '-':return(2);
break;
case '*':
case '/':return(3);
break;
case '^':return(4);
break;
case ')':return(5);
break;
}
}


inorder(node temp)
{
if(temp!=NULL)
{
inorder(temp->lchild);
printf("%c ",temp->info);
inorder(temp->rchild);
}
}

preorder(node temp)
{
if(temp!=NULL)
{
printf("%c ",temp->info);
preorder(temp->lchild);
preorder(temp->rchild);
}
}

postorder(node temp)
{
if(temp!=NULL)
{
postorder(temp->lchild);
postorder(temp->rchild);
printf("%c ",temp->info);
ev[++et]=temp->info;
}
}
evaluate()
{
int i,j=-1,a,b,ch[20];
for(i=0;ev[i]!='\0';i++)
{
if(isalnum(ev[i]))
ch[++j]=ev[i]-48;
else
{
b=ch[j];
a=ch[j-1];
switch(ev[i])
{
case '+':ch[--j]=a+b;
break;
case '-':ch[--j]=a-b;
break;
case '*':ch[--j]=a*b;
break;
case '/':ch[--j]=a/b;
break;
}
}
}
printf("\nValue = %d",ch[0]);
}

No comments:

Easy Hits

EasyHits4U.com - Your Free Traffic Exchange - 1:1 Exchange Ratio, 5-Tier Referral Program. FREE Advertising!

Bottom Square