正文
增加 11 行删除 11 行
6 行未改动789101112131415161718192021222324252627282930313233343536373839404142434445469 行未改动6 行未改动struct Node{int lch,rch;char op;}tree[maxN+1];//每个节点的左右子节点编号 ,每个节点的字符int nc=0;//节点数int build_tree(char *s,int x,int y)//x指当前字符串第一个字符的位置,y指最后一个字符的后面一位{int c1=-1,c2=-1,p=0;int u;if(y-x==1)//只有一个字符,建立单独节点{u=++nc;tree[u].lch=tree[u].rch=0;tree[u].op=s[x];return u;}for(int i=x;i<y;i++){switch(s[i]){case '(':p++;break;case ')':p--;break;//相当于一个栈,当'('和')'匹配时p=0case '+':case '-':if(!p) c1=i;break;case '*':case '/':if(!p) c2=i;break;//只有在括号外面的符号才可能是最后计算的;}//而*和/的优先级比+和-高,所以优先选择+,-}if(c1<0) c1=c2;//找不到括号外的加减号,就用乘除号if(c1<0)return build_tree(s, x+1, y-1);//说明整个表达式用括号括起来了,要去掉括号u=++nc;tree[u].lch=build_tree(s, x, c1);tree[u].rch=build_tree(s, c1+1, y);tree[u].op=s[c1];return u;}int main(){9 行未改动6 行未改动789101112131415161718192021222324252627282930313233343536373839404142434445469 行未改动6 行未改动struct Node{int lch,rch;char op;}tree[maxN+1];//每个节点的左右子节点编号 ,每个节点的字符int nc=0;//节点数int build_tree(char *s,int x,int y)//x指当前字符串第一个字符的位置,y指最后一个字符的后面一位{int c1=-1,c2=-1,p=0;int u;if(y-x==1)//只有一个字符,建立单独节点{u=++nc;tree[u].lch=tree[u].rch=0;tree[u].op=s[x];return u;}for(int i=x;i<y;i++){switch(s[i]){case '(':p++;break;case ')':p--;break;//相当于一个栈,当'('和')'匹配时p=0case '+':case '-':if(!p) c1=i;break;case '*':case '/':if(!p) c2=i;break;//只有在括号外面的符号才可能是最后计算的;}//而*和/的优先级比+和-高,所以优先选择+,-}if(c1<0) c1=c2;//找不到括号外的加减号,就用乘除号if(c1<0)return build_tree(s, x+1, y-1);//说明整个表达式用括号括起来了,要去掉括号u=++nc;tree[u].lch=build_tree(s, x, c1);tree[u].rch=build_tree(s, c1+1, y);tree[u].op=s[c1];return u;}int main(){9 行未改动