/* Expression tree from a postfix expression and tree
traversals using recursive and non-recursive algorithms
*/
#include<stdio.h>
#include<stdlib.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();
int main()
{
treenode *root=NULL,*p;
int x,op;
do
{
printf("\n\n1)Create\n2)Evaluate\n3)Quit");
printf("\nEnter Your Choice :");
scanf("%d",&op);
switch(op)
{
case 1: root=create();break;
case 2: printf("\Evaluated value=%d",evaluate(root));
break;
}
}while(op!=3);
}
int evaluate(treenode *T)
{
int val;
if(T!=NULL)
{
if(T->left==NULL && T->right==NULL)
{
printf("\nEnter the value of %c : ",T->data);
scanf("%d",&val);
return(val);
}
else
switch(T->data)
{
case '+': return(evaluate(T->left)+evaluate(T->right));
case '-': return(evaluate(T->left)-evaluate(T->right));
case '*': return(evaluate(T->left)*evaluate(T->right));
case '/': return(evaluate(T->left)/evaluate(T->right));
}
}
return(0);
}
treenode * create()
{
char a[50];
int i;
treenode *p,*q,*root;
stack s;
init(&s);
printf("\nEnter a postfix expression : ");
fflush(stdin);
scanf("%s",a);
fflush(stdin);
for(i=0;a[i]!='\0';i++)
{
if(isalpha(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);
}
No comments:
Post a Comment