PAT_A1130#Infix Expression
Source:
Description:
Given a syntax tree (binary), you are supposed to output the corresponding infix expression, with parentheses reflecting the precedences of the operators.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 20) which is the total number of nodes in the syntax tree. Then N lines follow, each gives the information of a node (the i-th line corresponds to the i-th node) in the format:
data left_child right_child
where
data
is a string of no more than 10 characters,left_child
andright_child
are the indices of this node's left and right children, respectively. The nodes are indexed from 1 to N. The NULL link is represented by −. The figures 1 and 2 correspond to the samples 1 and 2, respectively.
Figure 1 Figure 2
Output Specification:
For each case, print in a line the infix expression, with parentheses reflecting the precedences of the operators. Note that there must be no extra parentheses for the final expression, as is shown by the samples. There must be no space between any symbols.
Sample Input 1:
8
* 8 7
a -1 -1
* 4 1
+ 2 5
b -1 -1
d -1 -1
- -1 6
c -1 -1
Sample Output 1:
(a+b)*(c*(-d))
Sample Input 2:
8
2.35 -1 -1
* 6 1
- -1 4
% 7 8
+ 2 3
a -1 -1
str -1 -1
871 -1 -1
Sample Output 2:
(a*2.35)+(-(str%871))
Keys:
Code:
/*
Data: 2019-08-11 21:33:00
Problem: PAT_A1130#Infix Expression
AC: 16:51 题目大意:
打印中缀表达式
输入:
第一行给出,结点个数N<=20
接下来N行,给出结点i(1~N)的,键值,左孩子编号,右孩子编号(空子树-1) 基本思路:
静态树存储,输出中缀表达式
*/
#include<cstdio>
const int M=1e2;
struct node
{
char data[];
int l,r;
}infix[M]; void Express(int root, int rt)
{
if(root == -)
return;
if(root!=rt && (infix[root].l!=- || infix[root].r!=-))
printf("(");
Express(infix[root].l,rt);
printf("%s", infix[root].data);
Express(infix[root].r,rt);
if(root!=rt && (infix[root].l!=- || infix[root].r!=-))
printf(")");
} int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("Test.txt", "r", stdin);
#endif // ONLINE_JUDGE int n,h[M]={};
scanf("%d\n", &n);
for(int i=; i<=n; i++)
{
scanf("%s %d %d\n", infix[i].data, &infix[i].l, &infix[i].r);
if(infix[i].l!=-) h[infix[i].l]=;
if(infix[i].r!=-) h[infix[i].r]=;
}
for(int i=; i<=n; i++)
if(h[i]==)
Express(i,i); return ;
}
最新文章
- 电梯多媒体WinForm项目Q&;A总结
- STM
- 堪称最好的A*算法
- 更改Activity亮度
- css中position:relative的真正理解
- 在SQL 2012中使用和Oracle 一样的序列
- hdu 4372 第一类stirling数的应用/。。。好题
- .net环境下跨进程、高频率读写数据
- mysql进阶(十五) mysql批量删除大量数据
- requests 爬虫
- qsub
- python之list+字典练习
- Confluence 6 Confluence 安装目录
- [js]js中类的继承
- Linux系列教程(五)——Linux常用命令之链接命令和权限管理命令
- CS0433: 类型“Microsoft.Reporting.WebForms.ReportViewer”同时存在于“c:/WINDOWS/assembly/GAC_MSIL/Microsoft.ReportViewer.WebForms/8.0.0.0_ 标签: cassembly
- C++进阶--Koenig lookup 依赖于实参的名字查找
- 你所不知道的ASP.NET Core MVC/WebApi基础系列 (二)
- LAYOUT 注意点
- SVN合并时报错:Merge tracking not allowed with missing subtrees; try restoring these items