0
点赞
收藏
分享

微信扫一扫

leetcode每日-2022.03-19-606. 根据二叉树创建字符串

whiteMu 2022-03-19 阅读 62
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;
    }
};
举报

相关推荐

0 条评论