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.

61 lines
1.4 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 = 30;
int n;
string w[N];
int l[N], r[N], in[N];
int isleaf[N];
/*
题目描述:
给出中缀表达式的语法树 请你将后缀表达式输出 括号体现优先级 操作符不可用括号包含。
思路:
后缀表达式就是把运算符后置的表达式,可以抽象成一棵二叉树,其中的的节点有两种情况:
1有左右儿子
2只有右儿子
只有右儿子的情况就是负数啦~ 测试用例: - -1 6
然后就是找根,这个很简单,统计所有节点的入度,唯一的一个入度是 0 的节点就是根。
再写个简单的递归就可以了。
8
* 8 7
a -1 -1
* 4 1
+ 2 5
b -1 -1
d -1 -1
- -1 6
c -1 -1
输出样例1
(((a)(b)+)((c)(-(d))*)*)
*/
string dfs(int u) {
if (isleaf[u]) return "(" + w[u] + ")";
if (l[u] == -1 && r[u] != -1) return "(" + w[u] + dfs(r[u]) + ")"; // 负号
return "(" + dfs(l[u]) + dfs(r[u]) + w[u] + ")"; // 后缀表达式
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> w[i] >> l[i] >> r[i];
if (l[i] != -1) in[l[i]]++;
if (r[i] != -1) in[r[i]]++;
if (l[i] == -1 && r[i] == -1) isleaf[i] = 1; // 叶子
}
// 找根
int root;
for (root = 1; root <= n; root++)
if (!in[root]) break; // 入度为零的是根
cout << dfs(root) << endl;
return 0;
}