You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

101 lines
3.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
const int N = 1000010, M = N << 1;
#define ls e[h[u]] // 左儿子
#define rs e[ne[h[u]]] // 右儿子,由于表达式树的特殊性,有右儿子时一定有左儿子
stack<int> stk; // 节点号栈
int a[N], al = 25; // a[]:节点号对应的字符,0~25为数字a~z在表达式树中节点的编号,26及以上为每一个操作符的编号注意如果前后出现多次同一运算符它们的节点号是不一样的
// 链式前向星
int e[M], h[N], idx, w[M], ne[M];
void add(int a, int b, int c = 0) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
// 节点u
char out(int u) {
if (u >= 26) return a[u]; // 节点号大于等于26的是操作符+-*/
return u + 'a'; // a~z,记录的是0~25,输出需要加上偏移量'a'
}
// 前缀表达式
string preorder(int u) {
string ans = "";
if (h[u] == -1) {
ans += out(u);
return ans;
}
ans = out(u) + preorder(ls) + preorder(rs);
return ans;
}
// 中缀表达式
string inorder(int u) {
string ans = "";
if (h[u] == -1) {
ans += out(u);
return ans;
}
if (u >= 26) ans += "("; // 如果当前标记是一个操作符,打印左括号
ans += inorder(ls) + out(u) + inorder(rs);
if (u >= 26) ans += ")"; // 如果当前标记是运算符,则打印右括号
return ans;
}
// 后缀表达式
string postorder(int u) {
string ans = "";
if (h[u] == -1) {
ans += out(u);
return ans;
}
ans = postorder(ls) + postorder(rs) + out(u);
return ans;
}
// 通过后缀表达式构建表达式树
int build(string postfix) {
// 链式前向星初始化
memset(h, -1, sizeof h);
// 后缀表达式->表达式树,可以转化:前缀表达式,中缀表达式,后缀表达式
for (int i = 0; i < postfix.size(); i++) { // 枚举后缀表达式每一个字符
char c = postfix[i];
if (c == ' ') continue; // 如果后缀表达式中存在空格这样的字符,跳过
if (isalpha(c))
stk.push(c - 'a'); // 不是操作符,是数字,按字符-'a'的数字号入栈
else { // 如果是运算符+-*/
int x = stk.top(); // 取出两个节点
stk.pop();
int y = stk.top();
stk.pop();
a[++al] = c; // 操作符,申请一个节点号,并且,记录下来节点号与原字符的关系
add(al, x), add(al, y); // 由操作符向左右两个儿子连出边
stk.push(al); // 操作符节点入栈
}
}
return stk.top(); // 栈顶部的字符就是根
}
/*
Prefix Expression: *+ab*c+de
Postfix Expression: ab+cde+**
Infix Expression: ((a+b)*(c*(d+e)))
*/
int main() {
// 后缀表达式
string postfix = "ab+cde+**";
// 创建树
int root = build(postfix);
cout << preorder(root) << endl; // 输出前缀表达式
cout << postorder(root) << endl; // 输出后缀表达式
cout << inorder(root) << endl; // 输出中缀表达式
return 0;
}