二叉树是表达式处理的常用工具
其中每个叶子结点表示一个运算符;左子树是第一个运算数对应的表达式;右子树是第二个运算数对应的表达式;如何给表达式建立表达式树。有很多种方法,下面的方法是:找到“最后运算“的运算符(他是整棵表达式树的根);然后递归处理就是结果了;
一句话:每次找到最后计算的运算符,然后递归建树!

CODE
const int maxn =1000;
int lch[maxn], rch[maxn];char op[maxn];//每个结点的左右儿子编号和字符;
int nc=0;//结点数 node_conut
int bulid_tree(char *s,int x,int y)
{
int i,c1=-1,c2=-1,p=0;
int u;
if(y-x==1) //仅一个字符,建立单独结点
{
u=++nc;
lch[u]=0;rch[u]=0;
op[u]=s[x];
return u;
}
for(i=x;i<y;i++)
{
switch(s[i])
{
case '(':p++;break;
case ')':p--;break;
case '+':case '-':if(!p) c1=i;break;
case '*':case '/':if(!p) c2=i;break;
}
}
if(c1<0) c1=c2; //如果括号前没有加减号,就用乘除号码,整个表达式被一对括号括起来;
if(c1<0) return bulid_tree(s,x+1,y-1);
u=++nc;
lch[u]=build_tree(s,x,c1);
rch[u]=build_tree(s,c1+1,y);
op[u]=s[c1];
return u;
}