当前位置:网站首页>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;
}
边栏推荐
- ROS2安装时出现Connection failed [IP: 91.189.91.39 80]
- Cenos7 update MariaDB
- [ciscn2019 southeast China division]web11 1
- All in one 1251 - Fairy Island for medicine (breadth first search)
- P7 Day1 get to know the flask framework
- On Valentine's day, I drew an object with characters!
- Risk control and application of informatization project
- pytorch_demo1
- Explain cache consistency and memory barrier
- Flask login implementation
猜你喜欢

百人参与,openGauss开源社区这群人都在讨论什么?

我用字符画出了一个谷爱凌!

Realization of backstage brand management function

Flink1.15源码阅读flink-clients客户端执行流程(阅读较枯燥)

What are the differences or similarities between "demand fulfillment to settlement" and "purchase to payment"?

Flink1.15 source code reading Flink clients client execution process (reading is boring)

Functions and arrow functions

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

How to permanently set source
![[MRCTF2020]PYWebsite 1](/img/d4/2d9cd06abd7188add668cde77d3075.png)
[MRCTF2020]PYWebsite 1
随机推荐
SSTI template injection
Flask request data acquisition and response
Login to homepage function implementation
Forced login, seven cattle cloud upload pictures
Vertical align cannot align the picture and text vertically
Containerd failed to pull private database image (kubelet)
Fluent rendering mechanism - GPU thread rendering
[BJDCTF2020]EasySearch 1
ERP production operation control Huaxia
众昂矿业:新能源行业快速发展,氟化工产品势头强劲
Eval and assert execute one sentence Trojan horse
[penetration test tool sharing] [dnslog server building guidance]
Iterators and generators
pytorch_ demo1
“寻源到结算“与“采购到付款“两者有什么不同或相似之处?
Luogu super Mary game
[netding cup 2020 Qinglong group]areuserialz (buuctf)
Implementation of adding function of background user management display
03.使用引号来监听对象嵌套值的变化
Realization of specification management and specification option management functions