PAT A1130 Infix Expression (25 分)——中序遍历

Given a syntax tree (binary), you are supposed to output the corresponding infix 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.JPGinfix2.JPG
Figure 1 Figure 2

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))
 
 1 #include <stdio.h>
 2 #include <algorithm>
 3 #include <iostream>
 4 #include <map>
 5 #include <string>
 6 #include <vector>
 7 #include <set>
 8 #include <cctype>
 9 using namespace std;
10 const int maxn=30;
11 int n,m,k;
12 set<int> adj[maxn];
13 struct node{
14     string data;
15     int left;
16     int right;
17 };
18 node tree[maxn];
19 int isroot[maxn]={0};
20 int troot;
21 void midorder(int root){
22     if(root==-1)return;
23     if(root!=troot && !(tree[root].left==-1 && tree[root].right==-1))printf("(");
24     midorder(tree[root].left);
25     printf("%s",tree[root].data.c_str());
26     midorder(tree[root].right);
27     if(root!=troot && !(tree[root].left==-1 && tree[root].right==-1))printf(")");
28 }
29 int main(){
30     scanf("%d",&n);
31     for(int i=1;i<=n;i++){
32         string s;
33         int left,right;
34         cin>>s>>left>>right;
35         tree[i].data=s;
36         tree[i].left=left;
37         tree[i].right=right;
38         if(left!=-1)isroot[left]=1;
39         if(right!=-1)isroot[right]=1;
40     }
41     for(int i=1;i<=n;i++){
42         if(isroot[i]!=1){
43             troot=i;
44             break;
45         }
46     }
47     midorder(troot);
48 }
View Code

注意点:根据给定输入建一棵树,再输出中缀表达式,难点在于括号的处理。看了半天的思路是这样的:叶子节点如果是左子树就在这个叶子节点左子树上再加一个括号节点,是右子树叶子节点就在右子树上加个括号节点,中间的节点如果没有左子树也加个括号节点,最后看括号数量对不对在结尾补括号。看上去这思路还不错,但完全不知道该怎么写代码实现它,只好看大佬思路,发现思路大体上是对的,就是想实现的方式有问题。

在左叶节点的左边加括号,其实就是在中序遍历时判断这个节点是不是叶子节点和根节点,不是就在前后输出括号。脑子没转过来,难。

---------------- 坚持每天学习一点点
原文地址:https://www.cnblogs.com/tccbj/p/10422925.html