PAT甲级【2019年9月考题】——A1163 PostfixExpression【25】

7-3 Postfix Expression (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(20N(≤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.

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

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)%))+)

【声明】

  由于此题还未上PAT官网题库,故没有测试集,仅仅是通过了样例,若发现错误,感谢留言指正。

Solution:

  这道题与A1130 Infix Expression如出一辙,只不过换了一下位置。

  开始我重建了二叉树,后发现根本不用,因为给出的信息就是一个树的形状

  使用DFS遍历,先左,再右,后节点,

  唯一注意的就是缺少左孩子节点的情况【不可能只会出现缺少右孩子节点的情况,不然就不是等式】

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 using namespace std;
 5 int n, head = -1;
 6 struct Node
 7 {
 8     string val;
 9     int l, r;
10 }nodes[25];
11 string DFS(int root)
12 {
13     if (root == -1)    return "";
14     if (nodes[root].l == -1)//记住,只允许左子树为空,不能右子树为空,不然就不是个算式
15         return "(" + nodes[root].val + DFS(nodes[root].r) + ")";
16     else
17         return "(" + DFS(nodes[root].l) + DFS(nodes[root].r) + nodes[root].val + ")";
18 }
19 int main()
20 {
21     cin >> n;
22     vector<bool>isHead(n + 1, true);//找到头节点
23     for (int i = 1; i <= n; ++i)
24     {
25         string a;
26         int b, c;
27         cin >> a >> b >> c;
28         nodes[i] = { a,b,c };
29         isHead[(b == -1 ? 0 : b)] = isHead[(c == -1 ? 0 : c)] = false;
30     }
31     for (int i = 1; i <= n && head == -1; ++i)//找到头节点
32         if (isHead[i])head = i;
33     string res = DFS(head);
34     cout << res;
35     return 0;
36 }

猜你喜欢

转载自www.cnblogs.com/zzw1024/p/11964277.html