#include <iostream>
#include <vector>
#include <stack>
#include<string.h>
#include<cmath>
using namespace std;
struct tree
{
char c;
int n;
tree *left=NULL;
tree *right=NULL;
};
char buf[50][300];
char n[1000];
//测试数据 a+b*c
void postset(tree *p,char a[],int &y)
{
//cout<<a[y];
p->c=a[y--];
if(p->c>='a'&&p->c<='z')
return;
if(p->c=='*'||p->c=='-'||p->c=='+'||p->c=='/')
{
p->left=new tree;
p->right=new tree;
}
postset(p->right,a,y); //cout<<y;
postset(p->left,a,y);
}
int postheight(tree *p)
{
if(p!=NULL)
{
int a,b,x;
a=postheight(p->left);
b=postheight(p->right);
x=a>b?a:b;
return x+1;
}
}
void treeset(tree *p,int x,int floor,int s)
{
if(!p)return;
buf[floor][x]=p->c;
if(p->left&&p->right)
{
buf[floor+1][x-1]='/';
buf[floor+1][x+1]='\\';
}
treeset(p->left,x-s,floor+2,s>>1);
treeset(p->right,x+s,floor+2,s>>1);
}
int compute(tree *p)
{
if(!p)return 0;
int a,b;
a=compute(p->left);
b=compute(p->right);
if(p->c=='+')
{
return a+b;
}
else if(p->c=='-')
{
return a-b;
}
else if(p->c=='*')
{
return a*b;
}
else if(p->c=='/')
{
return a/b;
}
return p->n;
}
void setcompute(tree *p,char a,int n)
{
if(p)
{
if(p->c==a)
{
p->n=n; //cout<<n;
}
setcompute(p->left,a,n);
setcompute(p->right,a,n);
}
}
int main()
{
string s;
cin>>s;
int len=s.length();
int cur=0;
stack<char>S;
for(int i=0;i<len;++i)
{
if(s[i]>='a'&&s[i]<='z')
{
n[cur++]=s[i];
}
else if(s[i]=='(')
{
S.push(s[i]);
}
else if(s[i]==')')
{
while(S.top()!='(')
{
n[cur++]=S.top();
S.pop();
}
S.pop();
}
else if(s[i]=='+'||s[i]=='-')
{
while(!S.empty()&&S.top()!='(')
{
n[cur++]=S.top();
S.pop();
}
S.push(s[i]);
}
else if(s[i]=='*'||s[i]=='/')
{
while(!S.empty()&&(S.top()=='*'||S.top()=='/'))
{
n[cur++]=S.top();
S.pop();
}
S.push(s[i]);
}
}
while(!S.empty())
{
n[cur++]=S.top();
S.pop();
}
n[cur]='\0';
int y=strlen(n)-1;
tree *p=new tree;
postset(p,n,y);
int x,k;
char b;
cin>>x;
for(int i=0;i<x;i++)
{
cin>>b>>k;
setcompute(p,b,k);
}
//postprint(p); 后序测试成功
int height=postheight(p);
//cout<<height;
int hang=2*height-1;
int lie=pow(2,height)-1;
//int tag=(lie+1)>>2;
memset(buf,' ',sizeof(buf));
treeset(p,(lie+1>>1)-1,0,lie+1>>2);
cout<<n<<endl;
for(int i=0;i<hang;i++)
{
int j=299;
while(buf[i][j]==' ') j--;
buf[i][j+1]='\0';
cout<<buf[i]<<endl;
}
cout<<compute(p);
return 0;
}
头疼。。。。。
表达式·表达式树·表达式求值
最新推荐文章于 2021-11-04 16:37:11 发布