Skip to content

M297.二叉树的序列化与反序列化

dfs, bfs, https://leetcode.cn/problems/serialize-and-deserialize-binary-tree/

cpp
/**
 * 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 ret = "";
        queue<TreeNode*> q;
        q.push(root);
        while (!q.empty()) {
            auto u = q.front();
            q.pop();
            if (!u)
                ret += "-100000";
            else
                ret += to_string(u->val);
            if (u) {
                q.push(u->left);
                q.push(u->right);
            }
            ret += ' ';
        }
        return ret;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        // cout << data;
        stringstream ss(data);
        TreeNode* ret = nullptr;
        queue<TreeNode**> q;
        q.push(&ret);
        int u = 0;
        while (ss >> u) {
            auto cur = q.front();
            q.pop();
            if (u == -100000) {
                *cur = nullptr;
            } else {
                *cur = new TreeNode;
                (*cur)->val = u;
                q.push(&((*cur)->left));
                q.push(&((*cur)->right));
            }
        }
        return ret;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));