基于表达式求值(栈https://blog.youkuaiyun.com/asd20172016/article/details/80489304)
表达式树,先,中,后序遍历对应,表达式前,中,后缀表达式
叶子对应数
根对应两个数相操作
所以树中节点对应原来的数栈
改一改就行
至于求值,左子树值(根 操作)右子树值,递归求
#include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
int stn[100],tpn,tpa;
char sta[100];
typedef struct Node {
char val;
Node *lch,*rch;
Node(char val='#'):val(val),lch(NULL),rch(NULL){}
}*TNode;
TNode stt[100];
int tpt;
bool Cmp(char a,char b) {
return a=='(' ? 0 : (a=='*'||a=='/') >= (b=='*'||b=='/');
}
int calc(int a,char opt,int b) {
if (opt == '+') return a+b;
if (opt == '-') return a-b;
if (opt == '*') return a*b;
if (opt == '/') return a/b;
}
void Print() {
printf("STA: ");
int i;
for (i = 1; i <= tpa; i++)
cout << sta[i] << " ";
printf("\nSTN: ");
for (i = 1; i <= tpn; i++)
cout << stn[i] << " ";
puts("");
}
void Out() {
char c = sta[tpa--];
TNode tmp = new Node(c);
tmp->lch = stt[tpt-1];
tmp->rch = stt[tpt];
stt[--tpt] = tmp;
stn[tpn-1] = calc(stn[tpn-1],c,stn[tpn]);
tpn--;
}
void build(char *s,int len) {
int i;
for (i = 0; i < len; i++) {
char c = s[i];
if (c>='0' && c<='9') {
stn[++tpn] = c-'0';
stt[++tpt] = new Node(c);
} else if (c == ')') {
while(sta[tpa] != '(') Out();
tpa--;
} else if (c == '(') {
sta[++tpa] = c;
} else {
while(tpa && Cmp(sta[tpa],c)) Out();
sta[++tpa] = c;
}
// Print();
}
while(tpa) {
Out();
// Print();
}
}
int Tra(TNode t) {
if (t->val >= '0' && t->val <= '9') return t->val - '0';
return calc(Tra(t->lch),t->val,Tra(t->rch));
}
int main() {
char s[100];
cin >> s;
build(s,strlen(s));
printf("%d %d ",stn[tpn],Tra(stt[tpt]));
return 0;
}