当前位置:网站首页>4274. 后缀表达式
4274. 后缀表达式
2022-07-27 08:37:00 【追寻远方的人】
给定一个二叉表达式树,请你输出相应的后缀表达式,要求使用括号反映运算符的优先级。
输入格式
第一行包含整数 N,表示节点数量。节点编号 1∼N。
接下来 N 行,每行给出一个节点的信息(第 i 行对应第 i 个节点),格式为:
data left_child right_child
其中,data 是一个不超过 10 个字符的字符串,left_child 和 right_child 分别是该节点的左右子节点的编号。
没有子节点(即 NULL),则用 −1 表示。
下面两图分别对应给出的两个样例。


输出格式
在一行中输出答案,表达式符号之间不得有空格。
数据范围
1≤N≤20
输入样例1:
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))*)*)
输入样例2:
8
2.35 -1 -1
* 6 1
- -1 4
% 7 8
+ 2 3
a -1 -1
str -1 -1
871 -1 -1
输出样例2:
(((a)(2.35)*)(-((str)(871)%))+)
代码:
// 树求后缀表达式
#include <bits/stdc++.h>
using namespace std;
const int N = 25;
string v[N];
int l[N], r[N];
bool st[N];
int root;
void dfs(int u)
{
cout << '(';
if (l[u] != -1 && r[u] != -1) //当前为运算符
{
dfs(l[u]);
dfs(r[u]);
cout << v[u];
}
else if (l[u] == -1 && r[u] == -1) // 当前为数值
{
cout << v[u];
}
else // 只有右子树 当前为负号
{
cout << v[u];
dfs(r[u]);
}
cout << ')';
}
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> v[i] >> l[i] >> r[i];
if (l[i] != -1)
st[l[i]] = 1;
if (r[i] != -1)
st[r[i]] = 1;
}
for (int i = 1; i <= n; i++)
if (!st[i])
root = i;
dfs(root);
return 0;
}
边栏推荐
- Make a game by yourself with pyGame 01
- Cache consistency and memory barrier
- 无法获取下列许可SOLIDWORKS Standard,无法找到使用许可文件。(-1,359,2)。
- [NPUCTF2020]ReadlezPHP 1
- Idea remote debugging
- CMD command and NPM command
- 【uni-app高级实战】手把手带你学习一个纯实战复杂项目的开发1/100
- Apache SSI remote command execution vulnerability
- 开怀一笑
- “寻源到结算“与“采购到付款“两者有什么不同或相似之处?
猜你喜欢

Block, there is a gap between the block elements in the row

redis的string类型及bitmap

Login to homepage function implementation

pytorch_demo1

带宽 与 货币

OSI seven layer model and tcp/ip four layer (TCP and UDP) (notes)

阿里云国际版回执消息简介与配置流程

OPPO 自研大规模知识图谱及其在数智工程中的应用

I drew a Gu ailing with characters!

P7 Day1 get to know the flask framework
随机推荐
Cookie addition, deletion, modification and exception
Background image related applications - full, adaptive
Introduction to depth first search (DFS)
1178 questions of Olympiad in informatics -- ranking of grades
Use of flask
How to merge multiple columns in an excel table into one column
Vcenter7.0 managing esxi7.0 hosts
Set set
百人参与,openGauss开源社区这群人都在讨论什么?
说透缓存一致性与内存屏障
【uni-app高级实战】手把手带你学习一个纯实战复杂项目的开发1/100
Luogu super Mary game
User management - restrictions
How to view instances of software objects in QSIM?
Use of "PHP Basics" Boolean
Is online account opening safe? Want to know how securities companies get preferential accounts?
Virtual machine cloning
ERP production operation control Huaxia
Node installation and debugging
OSI seven layer model and tcp/ip four layer (TCP and UDP) (notes)