#include<iostream.h>
#include<string.h> #include<alloc.h> #include<conio.h> union info { int x; char ch; }; struct tree { char data; union info data2; struct tree *left,*right; }h; char exp[20]; int n; int check_precedency(char ch) { switch(ch) { case '+': case '-': return 1; case '*': case '/': return 2; default: return 3; } } int detect(char ch) { switch(ch) { case '+': case '-': case '*': case '/': return 1; default: return 0; } } int convert(char ch) { switch(ch) { case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; default: return 0; } } int convertCharToInt(char exp[],int l,int u) { char s[10]; int k=0; for(int i=l;i<u;i++,k++) { s[k]=exp[i]; } s[k]='\0'; float x=strtod(s,) } void Exp_tree(tree*q,int lb,int ub) { if(lb>ub)return; if(lb>=ub) { q->data=exp[lb]; q->data2.x=convert(exp[lb]); q->right=NULL; q->left=NULL; return; } int previous=4,precedency,position; for(int i=ub;i>=lb;i-- ) { precedency=check_precedency(exp[i]); if(previous>precedency) {position=i;previous=precedency;} } i=position; q->data2.ch=exp[i]; q->data=exp[i]; q->left=(tree*)malloc(sizeof(tree)); Exp_tree(q->left,lb,i-1); q->right=(tree*)malloc(sizeof(tree)); Exp_tree(q->right,i+1,ub); } int evaluate(tree* q) { switch(q->data2.ch) { case '+': return(q->left->data2.x+q->right->data2.x); case '-': return(q->left->data2.x-q->right->data2.x); case '*': return(q->left->data2.x*q->right->data2.x); case '/': return(q->left->data2.x/q->right->data2.x); } } void find(tree *q) { if(q->left==NULL||q->right==NULL)return; find(q->left); find(q->right); if(q->left->right==NULL&&q->left->left==NULL&&q->right->right==NULL&&q->right->left==NULL) { cout<<"\nLeaf Node.: "<<q->left->data2.x<<" "<<q->right->data2.x; q->data2.x=evaluate(q); cout<<"\tOperator.: "<<q->data<<"Result.: "<<q->data2.x; q->left=NULL; q->right=NULL; } } void print_inorder(struct tree *p) { if(p==NULL)return; print_inorder(p->left); cout<<" "<<p->data; print_inorder(p->right); } void print_preorder(struct tree *p) { if(p==NULL)return; cout<<p->data; print_preorder(p->left); print_preorder(p->right); } void print_postorder(struct tree *p) { if(p==NULL)return; print_postorder(p->left); print_postorder(p->right); cout<<p->data; } void main() { clrscr(); cout<<"\nEnter Infix Expression\n"; cin>>exp; n=strlen(exp); tree *q; q=(tree*)malloc(sizeof(tree)); Exp_tree(q,0,n-1); cout<<"\nInorder.: "; print_inorder(q); cout<<"\nPreorder.: "; print_preorder(q); cout<<"\nPostorder.: "; print_postorder(q); find(q); cout<<"\nFinal Solution.: "<<q->data2.x; getch(); } |
Tutorials | Tips and Trips | Engineering Concepts | Recent Technology | Invention and Innovation | and much more
Friday, August 31, 2012
c program for Expression Tree
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment