/*表达式树 建立过程 :找到“最后计算“的运算符(它是整棵表达式树的根),然后递归处理
* */
import java.util.Scanner;
public class ExpressionTree {
static final int MAXN = 1000;
int[] lch = new int[MAXN];
int[] rch = new int[MAXN];
char[] op = new char[MAXN];
char[] s = new char[MAXN];
int nc = 0; // 节点数
double res = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ExpressionTree et = new ExpressionTree();
while (scanner.hasNext()) {
String ss = scanner.nextLine();
et.s = ss.toCharArray();
et.build_tree(0, ss.length());
et.inOrder(1, ss.length());
System.out.println("result=" + et.res);
}
}
private int build_tree(int x, int y) {
int u = 0, c1 = -1, c2 = -1, p = 0;
if (y - x == 1) {// 仅一个字符,建立单独节点
u = ++nc;
lch[u] = rch[u] = 0;
op[u] = s[x];
return u;
}
for (int i = x; i < y; i++) {
switch (s[i]) {
case '(':
p++;
break;
case ')':
p--;
break;
case '+':
case '-':
if (p == 0) {// 括号外的加减号
c1 = i;
break;
}
case '*':
case '/':
if (p == 0) {// 括号外的乘除号
c2 = i;
break;
}
}
}
if (c1 < 0)
c1 = c2;// 括号外没有加减号 使用乘除号
if (c1 < 0)
return build_tree(x + 1, y - 1);// 括号外也没有乘除号 整个表达式被一个括号括起来
u = ++nc;
lch[u] = build_tree(x, c1);
rch[u] = build_tree(c1 + 1, y);
op[u] = s[c1];
return u;
}
private double inOrder(int i, int length) {
if (i == 0 || i > length)
return 0;
if (lch[i] == 0 && rch[i] == 0)
return op[i] - '0';
double t1 = inOrder(lch[i], length);
double t2 = inOrder(rch[i], length);
switch (op[i]) {
case '+':
res = t1 + t2;
break;
case '-':
res = t1 - t2;
break;
case '*':
res = t1 * t2;
break;
case '/':
res = t1 / t2;
break;
}
return res;
}
}
输入输出示例
4+3*(2-6)-8/2
result=-12.0