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.

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

思路:因为PAT答案比较多,个人会选择一些自己觉得自己写的比网上好的代码来分享
这题思路简单,因为符号运算则树的非叶结点只有2种情况,要么是只有右孩子结点,要
么是左右孩子都存在,所以右孩子一定存在而且每次输出右孩子前要输出'(',右孩子遍历之后要输出')',然后根节点情况除外就好。

代码:

#include <iostream>
#include <cstring>
using namespace std;
const int N=30;
struct node {
	string id;
	int l,r;
} Node[N];
int rootId;

void dfs(int x) {
	if(x==-1) return;
	//因为如果是符号结点就必须加括号而且一定有右孩子
	if(x!=rootId&&Node[x].r!=-1) printf("(");
	dfs(Node[x].l);
	printf("%s",Node[x].id.c_str());
	dfs(Node[x].r);
	if(x!=rootId&&Node[x].r!=-1) printf(")");
}

int main() {
	int n,l,r,hashT[N]= {0};
	cin>>n;
	string data;
	for(int i=1; i<=n; i++) {
		cin>>data>>l>>r;
		Node[i].id=data;
		Node[i].l=l;
		Node[i].r=r;
		if(l!=-1) hashT[l]=1;
		if(r!=-1) hashT[r]=1;
	}
	for(int i=1; i<=n; i++) {
		if(!hashT[i]) {
			rootId=i;
			break;
		}
	}
	dfs(rootId);
	return 0;
}
posted @ 2021-01-19 12:21  coderJ_ONE  阅读(61)  评论(0编辑  收藏  举报