PAT甲级1130-Infix Expression(DFS相关)
一.题目
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
wheredatais a string of no more than 10 characters,left_childandright_childare 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 | infix2.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))
二.题意分析
给定一颗表达式树,输出它的中缀表达式,需要对括号进行处理。可以看出如果左子树或者右子树不是叶子节点,就需要括号将子树包含进去。
三.代码部分
#include<bits/stdc++.h> using namespace std; struct node{ string data; int left=-1,right=-1;//定义初始化的值 }; node tree[25]; int n; bool isleaf(int v){//判断是否是叶节点 return tree[v].right==-1&&tree[v].left==-1; } void dfs(int v){ if(tree[v].left!=-1){//左子树存在 printf("%s",!isleaf(tree[v].left)?"(":"");//此结点的左子树不为空则加( dfs(tree[v].left);//递归左子树 printf("%s",!isleaf(tree[v].left)?")":"");//此结点的左子树不为空则加) } cout<<tree[v].data;//输出当前节点的信息(中序遍历) if(tree[v].right!=-1){//右子树存在 printf("%s",!isleaf(tree[v].right)?"(":""); dfs(tree[v].right); printf("%s",!isleaf(tree[v].right)?")":""); } } int main(){ cin>>n; bool child[n+1]={false};//初始化child数组 for(int i=1;i<=n;i++){ cin>>tree[i].data>>tree[i].left>>tree[i].right; if(tree[i].left!=-1)//标记child.left数组 child[tree[i].left]=true; if(tree[i].right!=-1)//标记child.right数组 child[tree[i].right]=true; } dfs(find(child+1,child+n+1,false)-child);//找到根节点,传入dfs函数 return 0; }