【PAT】1130.Infix Expression. (25)【树的中序遍历】

题目描述

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 and right_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 −1. The figures 1 and 2 correspond to the samples 1 and 2, respectively.

infix1.JPG infix2.JPG
翻译:每个输入文件包含一组测试数据。对于每组测试数据,第一行给定一个正整数N (≤ 20) ,表示语法树的节点总数。接下来N行,每一行按照以下格式给出一个节点(第i行代表第i个节点)的信息:
data left_child right_child
其中data是不超过10个字符的字符串,left_child和right_child分别是该节点的左子节点和右子节点的编号。节点编号从1到n,空节点用−1表示。图1和图2分别对应于样本1和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))


解题思路

按照中序遍历写, 如果不是根节点就在前后加个括号。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<string>
#include<vector>
#include<algorithm>
#define INF 99999999
#define bug puts("Hello\n")
using namespace std;
int N;
struct Node{
	string s;
	int l;
	int r;
	Node(){}
}node[25];
int fa[25],troot;
void inorder(int root){
	if(node[root].l==-1&&node[root].r==-1){
		cout<<node[root].s;
		return;
	}
	if(root!=troot)cout<<'(';
	if(node[root].l!=-1)inorder(node[root].l);
	cout<<node[root].s;
	if(node[root].r!=-1)inorder(node[root].r);
	if(root!=troot)cout<<')';
}
int main(){
	ios::sync_with_stdio(false);
	cin>>N;
	for(int i=1;i<=N;i++){
		cin>>node[i].s>>node[i].l>>node[i].r;
		fa[node[i].l]=i,fa[node[i].r]=i;
	}
	for(int i=1;i<=N;i++){
		if(fa[i]==0)troot=i;
	}
	inorder(troot);
	cout<<endl;
	return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值