只支持整数运算
浮点数运算之后更新
#include<iostream>
#include<string>
#include<string.h>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
using namespace std;
const int N = 1010;
int lch[N], rch[N]; //存储结点i的左、右孩子结点编号
string op[N];
int cnt = 0;// 结点个数
//字符串有效区间[x,y)
int getSum(int u)
{
if (op[u] == "+") return getSum(lch[u]) + getSum(rch[u]);
if (op[u] == "-") return getSum(lch[u]) - getSum(rch[u]);
if (op[u] == "*") return getSum(lch[u]) * getSum(rch[u]);
if (op[u] == "/") return getSum(lch[u]) / getSum(rch[u]);
int sum = 0;
for (int i = 0; i < op[u].size(); i++)
{
sum = sum * 10 + op[u][i] - '0';
}
return sum;
}
int BuildTree(string s, int x, int y)
{
int c1 = -1, c2 = -1, p = 0; //c1记录"最右"出现的+或-的位置, c2记录"最右"出现的*或/的位置
int u;
int num = 0; //数字字符个数
string temp;
for (int i = x; i < y; i++)
{
if (s[i] >= '0'&&s[i] <= '9') num++;
temp += s[i];
}
if (num == y - x) //区间内全是数字字符
{
u = ++cnt;
lch[u] = -1;
rch[u] = -1;
op[u] = temp;
return u;
}
for (int i = x; i < y; i++) //找到当前区间内表达式优先级最低的运算符,c1记录优先级最低的运算符所在位置
{
switch (s[i])
{
case '(':
p++;
break;
case ')':
p--;
break;
case '+':case '-':
if (p == 0) c1 = i; //p==0时,在括号外面,优先级较低
break;
case '*':case '/':
if (p == 0) c2 = i;
break;
default:
break;
}
}
if (c1 < 0) c1 = c2; //括号外不存在+或-,则*或/所在位置优先级最低,c1记录优先级最低的运算符所在位置
if (c1 < 0) //括号外也没有*或/,说明整个表达式最外面是一个括号
{
if (y - 1 > x + 1)
return BuildTree(s, x + 1, y - 1);
}
u = ++cnt;
lch[u] = BuildTree(s, x, c1); //左边为左子树,递归建树
rch[u] = BuildTree(s, c1 + 1, y); //右边为右子树
op[u] = s[c1];
return u;
}
void preOrder(int u) //前序遍历
{
if (u == -1) return;
cout << op[u] << " ";
preOrder(lch[u]);
preOrder(rch[u]);
}
void inOrder(int u) //中序遍历
{
if (u == -1) return;
inOrder(lch[u]);
cout << op[u] << " ";
inOrder(rch[u]);
}
void postOrder(int u) //后序遍历
{
if (u == -1) return;
postOrder(lch[u]);
postOrder(rch[u]);
cout << op[u] << " ";
}
int main()
{
cout << "输入中缀表达式:" << endl;
string s;
cin >> s;
BuildTree(s, 0, s.size());
cout << "前序遍历结果为:";
preOrder(1);
cout << endl;
cout << "中序遍历结果为:";
inOrder(1);
cout << endl;
cout << "后序遍历结果为:";
postOrder(1);
cout << endl;
cout << "表达式的结果为:" << getSum(1);
}