PAT甲级1130 Infix Expression (25分)|C++实现

一、题目描述

原题链接
Given a syntax tree (binary), you are supposed to output the corresponding infix expression, with parentheses reflecting the precedences of the operators.

Input Specification:

PAT甲级1130 Infix Expression (25分)|C++实现_第1张图片

​​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))

二、解题思路

树的中序遍历题,只要搞清楚括号放在什么时候输出即可。在中序遍历中,先遍历左子树再遍历右子树,我们知道叶子结点一定是运算元素,所以我们的括号要加在中序遍历前,以及中序遍历完成后。

三、AC代码

#include
#include
#include
#include
using namespace std;
const int maxn = 40;
struct Node
{
     
    string element;
    int lchild, rchild, parent = -1;
}node[maxn];
void inOrder(int root)
{
     
    if(root == -1)  return;
    bool flag = node[root].parent == -1 ||(node[root].lchild == -1 && node[root].rchild == -1) ? false : true;  //结点是运算数为false,节点是操作符时为true
    if(flag)    printf("(");    //如果是操作符,在中序遍历前就要加上左括号
    inOrder(node[root].lchild);
    printf("%s", node[root].element.c_str());
    inOrder(node[root].rchild);
    if(flag)    printf(")");    //中序遍历结束后,加上右括号
}
int main()
{
     
    int N;
    scanf("%d", &N);
    for(int i=1; i<=N; i++)
    {
     
        cin >> node[i].element >> node[i].lchild >> node[i].rchild;
        if(node[i].lchild != -1)    node[node[i].lchild].parent = i;
        if(node[i].rchild != -1)    node[node[i].rchild].parent = i;
    }
    int root;
    for(int i=1; i<=N; i++)
    {
     
        if(node[i].parent == -1)
        {
     
            root = i;
            break;
        }
    }
    inOrder(root);
    return 0;
}

你可能感兴趣的:(PAT,Advanced)