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
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))
基本思路:将一颗表达式树转换成中缀表达式。和17年408真题类似,可基于二叉树的中序遍历。对于括号的添加,只有表达式最外层和操作数两端不需加括号,因此除根结点和叶子节点外,遍历到其他结点时在遍历其左子树前加左括号,在遍历完右子树后加右括号即可。
c++
#include <iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cctype>
#include <algorithm>
#include<vector>
#include<queue>
#include<map>
#include<stack>
#include<sstream>
#include<set>
using namespace std;
const int maxn = 25;
string data[maxn];
bool visit[maxn]={false};
int n;
vector<vector<int> > node;
void inorder(int root,int deep){
if(root==-1) return;
else if(node[root][0]==-1 && node[root][1]==-1){
cout<<data[root];
}
else{
if(deep>1) printf("(");
inorder(node[root][0],deep+1);
cout<<data[root];
inorder(node[root][1],deep+1);
if(deep>1) printf(")");
}
}
int main()
{
scanf("%d",&n);
node.resize(n+1);
for(int i=1;i<=n;i++){
int a,b;
cin>>data[i]>>a>>b;
node[i].push_back(a);
node[i].push_back(b);
visit[a]=true;
visit[b]=true;
}
int root;
for(int i=1;i<=n;i++){
if(!visit[i]) {
root=i;
break;
}
}
inorder(root,1);
return 0;
}