1130 Infix Expression (25point(s))
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.
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:
8
* 8 7
a -1 -1
* 4 1
+ 2 5
b -1 -1
d -1 -1
- -1 6
c -1 -1
Sample Output:
(a+b)*(c*(-d))
Sample Input:
8
2.35 -1 -1
* 6 1
- -1 4
% 7 8
+ 2 3
a -1 -1
str -1 -1
871 -1 -1
Sample Output:
(a*2.35)+(-(str%871))
题目大意:
输入 N 个节点的树,每个节点包括数据和左右孩子
输出中缀表达式
设计思路:
输出中缀表达式,相当于中序遍历
- 左子树或右子树存在,需要
()
把左右子树括起来 - 把输出括号加入中序遍历
编译器:C (gcc)
#include <stdio.h>
struct node {
char d[15];
int left, right;
};
struct node tree[25];
int isleaf(int v)
{
return tree[v].left == -1 && tree[v].right == -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) ? ")" : "");
}
printf("%s", tree[v].d);
if (tree[v].right != -1) {
printf("%s", !isleaf(tree[v].right) ? "(" : "");
dfs(tree[v].right);
printf("%s", !isleaf(tree[v].right) ? ")" : "");
}
}
int main(void)
{
int n;
int root, i, child[25] = {0};
scanf("%d", &n);
for (i = 1; i <= n; i++) {
scanf("%s %d %d", tree[i].d, &tree[i].left, &tree[i].right);
if (tree[i].left != -1)
child[tree[i].left] = 1;
if (tree[i].right != -1)
child[tree[i].right] = 1;
}
root = 1;
while (child[root])
root++;
dfs(root);
return 0;
}