1、
2、
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
string tree2str(TreeNode* t) {
string ans="";
if(t==nullptr) return ans;
if(t!=nullptr) ans+=to_string(t->val);
if(t->left!=nullptr||t->right!=nullptr)
{
dfs(t->left,ans);
if(t->right!=nullptr)
{
dfs(t->right,ans);
}
}
return ans;
}
void dfs(TreeNode* root,string& s)
{
s+='(';
if(root!=nullptr)
{
s+=to_string(root->val);
if(root->left!=nullptr||root->right!=nullptr)
{
dfs(root->left,s);
if(root->right!=nullptr) dfs(root->right,s);
}
}
s+=')';
}
};