PAT(甲级)2019年秋季考试 7-3 Postfix Expression

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

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:ios

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
Figure 1
infix2.JPGexpress

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

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

题目限制:

image.png

题目大意:

现给定一颗语法树,要求输出其后缀表达式。this

算法思路:

后缀表达式实际上就是将a+b的操做符移到最后变为ab+,可是存在特殊状况,由于+和-既能够表明加减法,又能够表明正负号,因此这里得判断+,-是不是和后面的数字绑定在一块儿做为符号位的,判断的方法就是当前的左孩子是否为空,若是为空,那么就说明当前节点的操做符是一个符号位,和右子树的数值是一个总体。不然就是正常的先访问左子树,后访问右子树,最后访问操做符。
综上所述:spa

  • 一、若是当前节点没有左孩子,遍历根节点,而后再遍历右子树
  • 二、若是有左孩子,进行后序遍历。

而后就是对于该数根节点的获取,使用parent数组保存每个节点的根节点,初始为0,只要输入完毕后,其parent值依然为0的,就是根节点。最后进行后序遍历输出便可。3d

注意点:

  • 一、因为题目说了该树是一个语法树,不存在一个操做符为二元操做符,而且尚未左孩子的状况,也就是说没有左孩子的时候就必定是单元操做符。
  • 二、括号的输出是针对整个子树的,分三种状况,叶子节点,输出为(节点值),没有左孩子,输出为(根节点,右子树),有左孩子,输出为(左子树,右子树,根节点)

提交结果:

image.png

AC代码:

#include<cstdio>
#include<vector>
#include<iostream>

using namespace std;

struct Node{
    string c;
    int left,right;
}node[30];

int parent[30];

void postOrder(int root){
    if(root==-1) return;
    printf("(");
    if(node[root].left==-1){
        // 只有右子树,先输出当前节点,再输出右子树
        printf("%s",node[root].c.c_str());
        postOrder(node[root].right);
        printf(")");
    }else{
        // 左右子树都有,正常后序遍历便可
        postOrder(node[root].left);
        postOrder(node[root].right);
        printf("%s)",node[root].c.c_str());
    }
}

int main(){
    int N;
    scanf("%d",&N);
    Node no;
    for(int i=1;i<=N;++i){
        cin>>no.c>>no.left>>no.right;
        node[i] = no;
        parent[no.left] = i;
        parent[no.right] = i;
    }
    int root;
    for(int i=1;i<=N;++i){
        if(parent[i]==0){
            root = i;
            break;
        }
    }
    postOrder(root);
    return 0;
}
相关文章
相关标签/搜索