当前位置:网站首页>後綴錶達式(暑假每日一題 4)
後綴錶達式(暑假每日一題 4)
2022-07-23 15:49:00 【sweetheart7-7】
給定一個二叉錶達式樹,請你輸出相應的後綴錶達式,要求使用括號反映運算符的優先級。
輸入格式
第一行包含整數 N N N,錶示節點數量。節點編號 1 ∼ N 1∼N 1∼N。
接下來 N N N 行,每行給出一個節點的信息(第 i i i 行對應第 i i i 個節點),格式為:
data left_child right_child
其中,data 是一個不超過 10 10 10 個字符的字符串,left_child 和 right_child 分別是該節點的左右子節點的編號。
沒有子節點(即 NULL),則用 −1 錶示。
下面兩圖分別對應給出的兩個樣例。

輸出格式
在一行中輸出答案,錶達式符號之間不得有空格。
數據範圍
1 ≤ N ≤ 20 1≤N≤20 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<iostream>
#include<cstring>
using namespace std;
const int N = 30;
int n;
string a[N];
int l[N], r[N];
bool st[N];
void dfs(int u){
cout << '(';
if(l[u] == -1 && r[u] != -1){
cout << a[u];
dfs(r[u]);
}else{
if(l[u] != -1) dfs(l[u]);
if(r[u] != -1) dfs(r[u]);
cout << a[u];
}
cout << ')';
}
int main(){
cin >> n;
for(int i = 1; i <= n; i++){
cin >> a[i] >> l[i] >> r[i];
if(l[i] != -1) st[l[i]] = true;
if(r[i] != -1) st[r[i]] = true;
}
int head = -1;
for(int i = 1; i <= n; i++)
if(!st[i]) head = i;
dfs(head);
return 0;
}
边栏推荐
猜你喜欢

C语言经典例题-将输入的两位数转成英文

Gear 月度更新|6 月

在一个有序数组中查找具体的某个数字(二分查找or折半查找)

【Pygame实战】飞机射击大作:宇宙激战一触即发...这款超经典的射击游戏也该拿出来重启了~

Jsd-2204 session management filter day19

【攻防世界WEB】难度三星9分入门题(上):simple_js、mfw

What is the difference between server hosting and virtual host

7.13web safety operation

Remember SQL optimization once

Can multithreading optimize program performance?
随机推荐
Gear 月度更新|6 月
Modify SSH command line[ [email protected] ]Color
一个悄然崛起的国产软件,太强了!
数据治理浅析
aws篇4 一机一密
深入理解L1、L2正则化
【Try to Hack】sql注入 Less7 (into outfile和布尔盲注)
pydensecrf安装
《快速掌握QML》第四章 事件处理
[hiflow] regularly send Tencent cloud SMS sending group
bgp选路原则
[200 opencv routines] 225. Fourier descriptor for feature extraction
3D数学 - 矢量
作为测试人员,不能不懂的adb命令和操作
day1
第一篇 项目基本情况介绍
【HiFlow】定期发送腾讯云短信发送群
The current situation and history of it migrant workers
Start other independent programs through fmmonitoredprocess in unreal
专访|开源之夏新星牛学蔚