297. Serialize and Deserialize Binary Tree

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string res;
        serialize(root, res);
        return res;
    }
    void serialize(TreeNode* root, string &res) {
        if (root == NULL) {
            res += "#,";
            return;
        }
        res += to_string(root->val) + ",";
        serialize(root->left, res);
        serialize(root->right, res);
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        int idx = 0;
        return deserialize(data, idx);
    }
    TreeNode* deserialize(const string& data, int& idx) {
        if (idx >= data.length()) return NULL;
        int start = idx;
        while (data[idx] != ',')    idx++;
        string token = data.substr(start, idx-start);
        if (token == "#")   return NULL;
        TreeNode *root = new TreeNode(stoi(token));
        
        idx++;
        root->left = deserialize(data, idx);
        idx++;
        root->right = deserialize(data, idx);
        return root;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root));
原文地址:https://www.cnblogs.com/JTechRoad/p/9076445.html