#include <stdlib.h>#include<stdio.h>#include<string.h>#include<ctype.h>#defineMax_len 5typedefstructNode//node type definition{ Charoptr; intdata; structNode *Lchild; structNode *Rchild;} Btnode; Btnode*getnode (Char*STR,int&POS) {Btnode*createtree (Char*STR,int&POS); Btnode*p =NewBtnode; CharCH = str[0]; if(IsDigit (ch)) {inti =0; CharData[max_len]; while(IsDigit (ch=Str[i])) Data[i++] =ch; P->data =atoi (data); POS+=i; } Else if(ch = ='+'|| ch = ='-'|| ch = ='*'|| ch = ='/') {p->optr =ch; POS+=1; } Else if(ch = ='(') {pos+=1; P= Createtree (str+1, POS); } Else if(ch = =')') {pos+=1; returnNULL; } Else if(ch==' /') returnNULL; returnp; }intGetPriority (Charoptr) { Switch(optr) { Case '+': Case '-': return 1; Case '*': Case '/': return 2; } return 0;} Btnode*createtree (Char*STR,int&POS) { intPOS1 =0; Btnode*lchild = GetNode (str+pos1,pos1); Btnode*root = GetNode (str+pos1,pos1); Btnode*rchild = GetNode (str+pos1,pos1); Root->lchild =Lchild; Root->rchild =Rchild; Btnode*node; while((Node=getnode (str+POS1,POS1))) { if(GetPriority (ROOT->OPTR) > GetPriority (node->optr)) {Node->lchild=Root; Node->rchild=getnode (str+pos1,pos1); Root=node; } Else{node->lchild=root->Rchild; Root->rchild=node; Node->rchild=getnode (str+pos1,pos1); }} POS+=pos1; returnRoot;}intResult (Btnode *b)//Evaluating Expressions{ intn1,n2; Switch(b->optr) { Case'+': N1=result (B->lchild);//Calculating left dial hand expressionsN2=result (B->rchild);//Calculate right sub-expressionb->data=n1+n2; Break; Case'-': N1=result (B->lchild);//Calculating left dial hand expressionsN2=result (B->rchild);//Calculate right sub-expressionb->data=n1-n2; Break; Case'*': N1=result (B->lchild);//Calculating left dial hand expressionsN2=result (B->rchild);//Calculate right sub-expressionb->data=n1*n2; Break; Case'/': N1=result (B->lchild);//Calculating left dial hand expressionsN2=result (B->rchild);//Calculate right sub-expressionb->data=n1/n2; Break; default: returnB->data; } returnB->data;}voidMain () {Btnode*b=null,*q=NULL; Charstr[ -];//= "(20+30+5)";printf"Please enter an algebraic expression that meets the requirements:"); scanf ("%s", str); intn=0, i=0; while(str[i++]! =' /') n++; intpos =0; b=Createtree (Str,pos); //B = Create (str,n);printf"The value of the expression is:%d\n", result (b)); intA; scanf ("%d",&a);}
Tree nodes.