题目链接。
分析:
转换成表达式树,然后先序、中序、后序遍历。
AC代码如下:
#include <stdio.h>
#include <string.h> #define maxn 1000 int lch[maxn], rch[maxn], nc = ;
char op[maxn]; int build_tree(char *s, int x, int y) {
int i, c1 = -, c2 = -, p = ;
int u; if(y-x == ) {
u = ++nc;
lch[u] = rch[u] = ; 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 < ) c1 = c2;
if(c1 < ) return build_tree(s, x+, y-); u = ++nc;
lch[u] = build_tree(s, x, c1);
rch[u] = build_tree(s, c1+, y);
op[u] = s[c1]; return u;
} void pre_print(int u) {
if(u != ) {
printf("%c", op[u]);
pre_print(lch[u]);
pre_print(rch[u]);
}
} void in_print(int u) {
if(u != ) {
in_print(lch[u]);
printf("%c", op[u]);
in_print(rch[u]);
}
} void las_print(int u) {
if(u != ) {
las_print(lch[u]);
las_print(rch[u]);
printf("%c", op[u]);
}
} int main() {
char s[];
while(scanf("%s", s) == ) { build_tree(s, , strlen(s)-); pre_print();
putchar('\n'); in_print();
putchar('\n'); las_print();
putchar('\n');
} return ;
}