递归建立一个个表达式树。
例如:1*1+2*2;+ 的左子树为根为1的树;+ 的右子树为根为2的树;* / 优先级高先建树 + -优先级低后建树
中序遍历计算结果
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char str[2000];
int len;
struct node{
int father;
int left;
int right;
}f[1020];
int y[1020];//标记 让每个运算符只建一次树
int find_set(int loc)//找到代表节点
{
if(f[loc].father!=loc)
return find_set(f[loc].father);
else return f[loc].father;
}
void merge(int i)//合并前一位的树和后一位的树
{
int k;
k=find_set(i-1);
f[i].left=k;f[k].father=i;//让前一位的代表节点作为i的左子树
k=find_set(i+1);
f[i].right=k;f[k].father=i;//让后一位的代表节点作为i的右子树
}
void settree(int start)
{//总体上来说优先级高的运算先建树等后面就会被其它优先级低的运算和并
int i;
int finish;
for(i=start;i<=len+1;i++)//寻找的括起来的区域
{
if(str[i]=='('&&y[i]==1)
{y[i]=0;f[i+1].left=i;f[i].father=i+1;settree(i+1);}//找的前括号递归并标记
if(str[i]==')'&&y[i]==1)
{y[i]=0;f[i-1].right=i;f[i].father=i-1;finish=i;break;}//找到未标记后括号跳出循环
}
for(i=start;i<=finish;i++)
{
if((str[i]=='*'||str[i]=='/')&&y[i]==1)//先做乘除
{y[i]=0;merge(i);}
}
for(i=start;i<=finish;i++)
{
if((str[i]=='+'||str[i]=='-')&&y[i]==1)//后做加减
{y[i]=0;merge(i);}
}
}
void output(int root)//后序输出
{
if(f[root].left!=-1)
output(f[root].left);
if(f[root].right!=-1)
output(f[root].right);
if(root>0&&root<len+1&&str[root]!='('&&str[root]!=')')
printf("%c",str[root]);
}
int main()
{
int T;
int i,k;
int p;
scanf("%d",&T);
while(T--)
{
k=0;
scanf("%s",str+1);
len=strlen(str+1);
str[0]='(';
str[len+1]=')';
str[len+2]='\0';
// puts(str);
for(i=0;i<=len+1;i++)
{f[i].father=i;f[i].left=-1;f[i].right=-1;y[i]=1;}//让每一个节点初始时指向自己本身
settree(1);
p=find_set(1);
// for(i=1;i<=len;i++)
// printf("%d:%d %d %d\n",i,f[i].left,f[i].right,f[i].father);
output(p);
printf("\n");
}
return 0;
}