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

whiteMu

关注

阅读 62

2022-03-19

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)

0 0 举报