分数 25
全屏浏览题目
切换布局
作者 陈越
单位 浙江大学
Given a syntax tree (binary), you are supposed to output the corresponding postfix 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.
Figure 1 | Figure 2 |
Output Specification:
For each case, print in a line the postfix expression, with parentheses reflecting the precedences of the operators.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)%))+)
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
注意:其中+,-两个符号既可以表示加减也可以表示正负,当表示正负的时候该节点一定是没有左孩子的
#include<bits/stdc++.h>
using namespace std;
const int N=25;
int n,l[N],r[N],exist[N];
string w[N];
string post(int u){
string left,right;
if(l[u]==-1&&r[u]==-1)return w[u];//若是根结点则返回该结点符号
if(l[u]!=-1&&r[u]!=-1){//若左右孩子都有
left="("+post(l[u])+")";//记录左子树及加上对应括号
right="("+post(r[u])+")";//记录右子树及加上对应的括号
return left+right+w[u];//返回左孩子,右孩子和该节点的符号
}
else if(w[u]=="-"||w[u]=="+"&&l[u]==-1){//若该节点是+,-两个符号且没有左孩子,说明两个符号表示正负
right="("+post(r[u])+")";//只用遍历右子树并记录即可
return w[u]+right;//返回该符号和右子树
}
}
int main(){
cin>>n;
for(int i=1;i<=n;i++){
cin>>w[i]>>l[i]>>r[i];
exist[l[i]]=exist[r[i]]=1;//记录出现过的结点
}
int root;
for(int i=1;i<=n;i++)if(!exist[i])root=i;//没出现的结点是根结点
cout<<"("+post(root)+")";
return 0;
}