题目:输入一个表达式(保护括号和四则运算),输出前中后序遍历。
思路:通过求出波兰表达式(后序),再进行二叉树建树的操作。
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100;
int mp[50], n;
string s, posodr;
struct node {
int l, r;
char val;
} tr[MAXN];
void getPosorder() {
stack<char> stk;
for (int i = 1; i <= n; i++) {
if (isdigit(s[i])) posodr += s[i];
else if (s[i] == '(') stk.push('(');
else if (s[i] == ')') {
while (stk.top() != '(') {
posodr += stk.top();
stk.pop();
}
stk.pop();
} else {
while (stk.size() && mp[stk.top()] >= mp[s[i]]) {
posodr += stk.top();
stk.pop();
}
stk.push(s[i]);
}
}
while (stk.size() != 0) {
posodr += stk.top();
stk.pop();
}
}
void buildTree() {
posodr = " " + posodr;
stack<int> stk;
for (int i = 1; i <= posodr.size() - 1; i++) {
tr[i].val = posodr[i];
if (isdigit(posodr[i])) stk.push(i);
else {
tr[i].r = stk.top();
stk.pop();
tr[i].l = stk.top();
stk.pop();
stk.push(i);
}
}
return;
}
string ans1, ans2, ans3;
void printTree(int x) {
ans1.push_back(tr[x].val);
if (tr[x].l) printTree(tr[x].l);
ans2.push_back(tr[x].val);
if (tr[x].r) printTree(tr[x].r);
ans3.push_back(tr[x].val);
return;
}
int main() {
mp['+'] = 1, mp['-'] = 1, mp['*'] = 2, mp['/'] = 2;
cin >> s;
n = s.size() - 1;
s = " " + s;
getPosorder();
buildTree();
printTree(posodr.size() - 1);
cout << ans1 << "\n" << ans2 << "\n" << ans3;
return 0;
}