C++ 根据二叉树创建字符串

根据二叉树创建字符串

题目描述
C++ 根据二叉树创建字符串_第1张图片
题目来源:力扣

class Solution {
public:
    string tree2str(TreeNode* root)
    {
        string s;
        _tree2str(root,s);
        return s;
    }
    void _tree2str(TreeNode* root,string& str) {
        if(root == nullptr)
        {
            return ;
        }
        str += to_string(root->val);
        if(root->left || root->right)
        {
            str += '(';
           _tree2str(root->left,str);
            str += ')';
        }
       if(root->right)
       {
            str += '(';
            _tree2str(root->right,str);
            str += ')';
       }
       
    }
};

你可能感兴趣的:(C++,1024程序员节,c++,leetcode)