A1163 Postfix Expression (25 points)

如同 A1130 Infix Expression 树的遍历判断

1. 原文

Given a syntax tree (binary), you are supposed to output the corresponding postfix expression, with parentheses reflecting the precedences of the operators.

1.0.1. 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:

1
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.

image
image

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

1
2
3
4
5
6
7
8
9
8
* 8 7
a -1 -1
* 4 1
+ 2 5
b -1 -1
d -1 -1
- -1 6
c -1 -1

Sample Output 1

1
(((a)(b)+)((c)(-(d))*)*)

Sample Input 2

1
2
3
4
5
6
7
8
9
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

1
(((a)(2.35)*)(-((str)(871)%))+)

2. 解析思路

类比 A1130

采用后序遍历方法,当左子树存在时,采用左右根的遍历方法,当左子树不存在时,采用根右的遍历方法

3. AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include<cstdio>
const int maxn = 30;
int degree[maxn]={};
struct node{
char data[20];
int lchild,rchild;
}v[maxn];
int getIdx(char ch[]){
int num = 0;
for (int i = 0; ch[i] != '\0'; ++i)
{
num = num*10+ch[i]-'0';
}
return num;
}
char str[10];
void postOrder(int root){
if (root == -1)
{
return;
}
else if (v[root].lchild==-1)
{
printf("(");
printf("%s",v[root].data);
postOrder(v[root].rchild);
printf(")");
}else{
printf("(");
postOrder(v[root].lchild);
postOrder(v[root].rchild);
printf("%s",v[root].data);
printf(")");
}
}
int main(){
freopen("A1163.txt","r",stdin);
int n;
scanf("%d",&n);
for (int i = 1; i <= n; ++i)
{
scanf("%s%s",v[i].data,str);
if (str[0]=='-')
{
v[i].lchild=-1;
}else{
int a = getIdx(str);
degree[a]++;
v[i].lchild=a;
}
scanf("%s",str);
if (str[0]=='-')
{
v[i].rchild=-1;
}else{
int a = getIdx(str);
degree[a]++;
v[i].rchild=a;
}
}
int root = 0;
for (int i = 1; i <= n; ++i)
{
if (degree[i]==0)
{
root = i;
break;
}
}
postOrder(root);
printf("\n");
return 0;
}
本文结束  感谢您的阅读
  • 本文作者: Wang Ting
  • 本文链接: /zh-CN/2019/10/30/A1163/
  • 发布时间: 2019-10-30 22:38
  • 更新时间: 2021-10-29 14:11
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!