1130 Infix Expression (25 分)-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.
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))
题目大意:
给定一个二叉树,要求输出它的中缀表达式,并在合适的地方加上括号表示优先级
算法分析:
用结构体存储结点的相关信息,包括data、leftChild、rightChild。遍历所有的孩子结点,找到其中没有出现的编号,标记为root。用深度优先搜索完成树的中序遍历。
难点在于如何输出括号,实际上所有非根结点的符号结点(指右子树不为空的结点,因为不存在左子树存在,右子树不存在的情况,因为这在算术表达式中不成立)左右必有括号,扩住它左右两边的字符串。我们抓住这一点,在遇到非根结点的符号结点时先输出"(",遍历完其左右子树后再输出")"
AC代码:
#include<bits/stdc++.h>
using namespace std;
struct node{
string data;
int leftChild, rightChild;
};
int nodeNum,root;
node nodeSet[25];
/*只要是非根结点的符号结点一定有括号,利用这个特点可以将大问题化简*/
void DFS(int index){
if(index!=root&&(nodeSet[index].rightChild!=-1))
//右子树不空就代表它是一个符号结点,因为不存在只有左边没有右边的情况
printf("(");
/*遇到非根结点的符号结点,先输出(,遍历完其左右子树后再输出)*/
if(nodeSet[index].leftChild!=-1)
DFS(nodeSet[index].leftChild);
cout << nodeSet[index].data;
if(nodeSet[index].rightChild!=-1)
DFS(nodeSet[index].rightChild);
if(index!=root&&(nodeSet[index].rightChild!=-1))
printf(")");
}
int main(){
cin >> nodeNum;
int temp[nodeNum+1] = {0};
for (int i = 1; i <= nodeNum;i++){
cin >> nodeSet[i].data >> nodeSet[i].leftChild >> nodeSet[i].rightChild;
temp[nodeSet[i].leftChild] = i;
temp[nodeSet[i].rightChild] = i;
}
for (int i = 1; i <= nodeNum;i++){
if(temp[i]==0){
root = i;
break;
}
}//找到孩子结点中没有出现过的编号,该编号为root
DFS(root);
}
标签:25,结点,PAT,真题,int,index,leftChild,nodeSet,root 来源: https://blog.csdn.net/weixin_48954087/article/details/113867001