Serialize and Deserialize Binary Tree

ostringstream;
istringstream;
class Codec {
public:

    string serialize(TreeNode* root) {
        ostringstream out;
        serialize(root, out);
        return out.str();
    }

    TreeNode* deserialize(string data) {
        istringstream in(data);
        return deserialize(in);
    }

private:

    void serialize(TreeNode* root, ostringstream& out) {
        if (root) {
            out << root->val << ' ';
            serialize(root->left, out);
            serialize(root->right, out);
        } else {
            out << "# ";
        }
    }

    TreeNode* deserialize(istringstream& in) {
        string val;
        in >> val;
        if (val == "#")
            return nullptr;
        TreeNode* root = new TreeNode(stoi(val));
        root->left = deserialize(in);
        root->right = deserialize(in);
        return root;
    }
};

http://www.cplusplus.com/reference/sstream/istringstream/istringstream/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
// Sean
class Codec {
public:
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        // preorder serialize
        string str;
        serialize(root, str);

        cout << str << endl;

        return str;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        return new TreeNode(1);      
    }

private:
    void serialize(TreeNode* root, string& str) {
        if (!root) {
            str.append("-1");
            str.append(" ");
            return;
        }

        str.append( to_string(root->val) );
        str.append(" ");
        serialize(root->left, str);
        serialize(root->right, str);

        return;
    }


};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));

results matching ""

    No results matching ""