码出自已的代码风格!(非叶子节点且不是根节点就要加括号)
#include <iostream>
#include <vector>
#include <tuple>
#include <algorithm>
using namespace std;
int n, l, r;
string val;
struct TreeNode {
string val;
TreeNode* left;
TreeNode* right;
TreeNode() : val(" "), left(nullptr), right(nullptr) {};
TreeNode(string _val) : val(_val), left(nullptr), right(nullptr) {};
TreeNode(string _val, TreeNode* _left, TreeNode* _right) : val(_val), left(_left), right(_right) {};
~TreeNode() {};
};
TreeNode* buildTree(const vector<tuple<string, int, int>>& node_infos, int index) {
// recursion exit condition
if (index == -1) return nullptr;
auto root = new TreeNode(get<0>(node_infos[index]));
root->left = buildTree(node_infos, get<1>(node_infos[index]));
root->right = buildTree(node_infos, get<2>(node_infos[index]));
return root;
}
void traverse(const TreeNode* node, const TreeNode* root) {
if (!node) return;
bool flag = false;
if ((node->left || node->right) && node != root) {
putchar('(');
flag = true;
}
traverse(node->left, root);
cout << node->val;
traverse(node->right, root);
if (flag) putchar(')');
}
int main(void) {
cin >> n;
vector<tuple<string, int, int>> node_infos(n + 1);
vector<int> hasParent(n + 1);
for (int i = 1; i <= n; ++i) {
cin >> val >> l >> r;
node_infos[i] = {val, l, r};
if (l != -1) hasParent[l] = 1;
if (r != -1) hasParent[r] = 1;
}
int root_id = 1;
while (hasParent[root_id]) ++root_id;
auto root = buildTree(node_infos, root_id);
traverse(root, root);
return 0;
}