C++ preorder approach


  • 0
    J
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string s = "";
        serialize(root, s);
        return s;
    }
    
    void serialize(TreeNode* root, string &s) {
        if(!root) {
            s += "NULL,";
            return;
        }
        
        s += to_string(root->val) + ",";
        serialize(root->left, s);
        serialize(root->right, s);
    }
    
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        istringstream iss (data);
        return deserialize(iss);
    }
    
    TreeNode* deserialize(istringstream& iss) {
        string token;
        getline(iss, token, ',');
        
        if(token == "NULL")
            return NULL;
        
        TreeNode* newNode = new TreeNode(stoi(token));
        newNode->left = deserialize(iss);
        newNode->right = deserialize(iss);
        return newNode;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.