class Solution {
public:
void change(TreeNode* root, string& s){
if (root->left != nullptr){
s += '(' + to_string(root->left->val);
change(root->left, s);
s += ')';
}
if (root->right != nullptr){
if (root->left == nullptr)
s += "()";
s += '(' + to_string(root->right->val);
change(root->right, s);
s += ')';
}
}
string tree2str(TreeNode* root) {
string res;
if (root == nullptr)
return "";
res += to_string(root->val);
TreeNode* p = root;
change(p, res);
return res;
}
};