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))
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 <iostream>
#include <vector>
using namespace std;
vector<pair<int, int>> sons;
vector<string> value;
string infix(int node)
{
if (node == -1) return "";
else if (sons[node] == make_pair(-1,-1)) return value[node];
return "(" + infix(sons[node].first) + value[node] + infix(sons[node].second) + ")";
}
int main()
{
int n, root;
cin >> n;
root = n * (n + 1) / 2;
sons.resize(n + 1), value.resize(n + 1);
for (int i = 1; i <= n; ++i)
{
cin >> value[i] >> sons[i].first >> sons[i].second;
root -= (sons[i].first == -1 ? 0 : sons[i].first) + (sons[i].second == -1 ? 0 : sons[i].second);
}
string ans = infix(root);
if (n == 1) cout << ans;
else cout << ans.substr(1, ans.size() - 2);
}