思路
除了根节点的操作符不加括号,其他操作符都要加括号。
不需要对左子树为空表示的数单独处理,因为总是在操作符的时候会添加一层括号。若单独处理,则得考虑到左子树为空的节点可能是根节点。
代码
#include<bits/stdc++.h>
using namespace std;
vector<int> pa;
vector<string> datas;
vector<pair<int,int>> children;
bool is_leaf(int root) {
return children[root].first == -1 && children[root].second == -1;
}
int root_ = -1;
string inorder(int root) {
string d = datas[root];
if(is_leaf(root))
return d;
int left = children[root].first;
int right = children[root].second;
string lstr, rstr;
if(left != -1)
lstr = inorder(left);
if(right != -1)
rstr = inorder(right);
if(root_ == root)
return lstr + d + rstr;
return "(" + lstr + d + rstr + ")";
}
int main() {
int n;
cin >> n;
children.resize(n + 1,{-1, -1});
pa.resize(n + 1, -1);
datas.resize(n + 1);
for(int i = 1; i <= n; ++i) {
string d;
int left, right;
cin >> d >> left >> right;
if(left != -1) {
children[i].first = left;
pa[left] = i;
}
if(right != -1) {
children[i].second = right;
pa[right] = i;
}
datas[i] = d;
}
root_ = -1;
for(int i=1; i <=n; ++i) {
if(pa[i] == -1) {
root_ = i;
break;
}
}
assert(root_ != -1);
cout << inorder(root_) << endl;
}