#include<cstdlib>
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include <algorithm>
#include<vector>
#include<set>
#define LL long long
#define inf 0x7fffffff
#define E 1e-9
#define M 100
#define N 10010
using namespace std;
char str[N];
char op[N];
int lch[N],rch[N],top;
int build(int x,int y)
{
if(y-x==1)
{
top++;
op[top]=str[x];
lch[top]=0;
rch[top]=0;
return top;
}
int c1=-1,c2=-1,p=0;
for(int i=x;i<y;i++)
{
switch (str[i])
{
case '*':case '/':if(!p)c2=i;break;
case '+':case '-':if(!p)c1=i;break;
case '(':p++;break;
case ')':p--;break;
}
}
if(c1<0)c1=c2;
if(c1<0)
return build(x+1,y-1);
int u=++top;
op[u]=str[c1];
lch[u]=build(x,c1);
rch[u]=build(c1+1,y);
return u;
}
void pre(int k)
{
printf("(");
if(lch[k]) pre(lch[k]);
printf("%c",op[k]);
if(rch[k]) pre(rch[k]);
printf(")");
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("ex.in","r",stdin);
#endif
while(gets(str)!=NULL)
{
top=0;
build(0,strlen(str));
pre(1);//从1开始
cout<<endl;
cout<<endl;
}
return 0;
}
表达式树
最新推荐文章于 2022-04-18 15:50:18 发布