1162 Postfix Expression (25 point(s))
☆
题目
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.
infix1.JPG infix2.JPG
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)%))+)
思路
题意
给出一个语法树,按照后缀表达输出。输入n个结点,按照结点值,左孩子index,右孩子index的格式读入(结点读入的次序即其index)。输出格式为每个表达式都用()括起来表示优先级。遇到结点无左孩子有右孩子的情况,表达式变为前缀表达。
思路
用tree[][2]建立index树,用node[]记录每个index对应的结点值。读入输入的时候建树,然后遍历树的时候输出。遍历树分三种情况:
- 结点同时有左右孩子,后序遍历输出
- 结点无左孩子有右孩子,先输出结点值再遍历右子树
- 结点无孩子,直接输出结点值。
注意每次遍历的头尾要输出(
和)
解法
#include<bits/stdc++.h>
using namespace std;
int n, root;
int tree[25][2], visited[25] = { 0 };
string node[25];
void traverse(int index) {//左1右1,左0右1,左0右0
printf("(");
if (tree[index][0] > 0) {//左1
traverse(tree[index][0]);//左子树
traverse(tree[index][1]);//右子树
printf("%s", node[index].c_str());
}
else if (tree[index][1] > 0) {//左0右1
printf("%s", node[index].c_str());//输出结点本身
traverse(tree[index][1]);//右子树
}
else {//左0右0
printf("%s", node[index].c_str());//输出结点本身
}
printf(")");
}
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
string data;
cin >> data;
node[i] = data;
int left, right;
scanf("%d%d", &left, &right);
tree[i][0] = left;
tree[i][1] = right;
visited[left] = visited[right] = 1;
}
for (int i = 1; i <= n; i++)
if (visited[i] == 0) {
root = i;
break;
}
traverse(root);
printf("\n");
return 0;
}
注意
- 当左孩子无右孩子有的时候均是特殊表达