#include<bits/stdc++.h>
using namespace std;
string s;
typedef struct node
{
int data;
struct node *lc,*rc;
} node,*link;
void creat(link &L)
{
cin>>s;
if(s[0]=='#')
L=NULL;
else
{
int p=0;
if(s[0]=='+')
p=-1;
else if(s[0]=='-')
p=-2;
else if(s[0]=='*')
p=-3;
else if(s[0]=='/')
p=-4;
else
{
int i=0,n=s.size();
while(i<n)
{
p=p*10+(s[i]-'0');
i++;
}
}
L=new node;
L->data=p;
creat(L->lc);
creat(L->rc);
}
}
void print(link L)
{
if(L)
{
if(L->data>=0) printf("%d",L->data);
else
{
printf("(");
print(L->lc);
if(L->data==-1) printf("+");
else if(L->data==-2) printf("-");
else if(L->data==-3) printf("*");
else printf("/");
print(L->rc);
printf(")");
}
}
}
int main()
{
while(cin>>s)
{
link L;
int p=0;
if(s[0]=='+')
p=-1;
else if(s[0]=='-')
p=-2;
else if(s[0]=='*')
p=-3;
else if(s[0]=='/')
p=-4;
else
{
int i=0,n=s.size();
while(i<n)
{
p=p*10+(s[i]-'0');
i++;
}
}
L=new node;
L->data=p;
creat(L->lc);
creat(L->rc);
print(L);
printf("\n");
}
}
表达式树的创建与输出
最新推荐文章于 2025-04-04 10:39:52 发布