1. 程式人生 > >[LeetCode] Serialize and Deserialize Binary Tree 二叉樹的序列化和去序列化

[LeetCode] Serialize and Deserialize Binary Tree 二叉樹的序列化和去序列化

Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

For example, you may serialize the following tree

    1
   / \
  2   3
     / \
    4   5

as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

Credits:
Special thanks to @Louis1992 for adding this problem and creating all test cases.

這道題讓我們對二叉樹進行序列化和去序列化的操作。序列化就是將一個數據結構或物體轉化為一個位序列,可以存進一個檔案或者記憶體緩衝器中,然後通過網路連線在相同的或者另一個電腦環境中被還原,還原的過程叫做去序列化。現在讓我們來序列化和去序列化一個二叉樹,並給了我們例子。這題有兩種解法,分別為先序遍歷的遞迴解法和層序遍歷的非遞迴解法。先來看先序遍歷的遞迴解法,非常的簡單易懂,我們需要接入輸入和輸出字串流istringstream和ostringstream,對於序列化,我們從根節點開始,如果節點存在,則將值存入輸出字串流,然後分別對其左右子節點遞迴呼叫序列化函式即可。對於去序列化,我們先讀入第一個字元,以此生成一個根節點,然後再對根節點的左右子節點遞迴呼叫去序列化函式即可,參見程式碼如下:

解法一:

class Codec {
public:
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ostringstream out;
        serialize(root, out);
        return out.str();
    }
    // Decodes your encoded data to tree.
    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;
    }
};

另一種方法是層序遍歷的非遞迴解法,這種方法略微複雜一些,我們需要藉助queue來做,本質是BFS演算法,也不是很難理解,就是BFS演算法的常規套路稍作修改即可,參見程式碼如下:

解法二:

class Codec {
public:
    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        ostringstream out;
        queue<TreeNode*> q;
        if (root) q.push(root);
        while (!q.empty()) {
            TreeNode *t = q.front(); q.pop();
            if (t) {
                out << t->val << ' ';
                q.push(t->left);
                q.push(t->right);
            } else {
                out << "# ";
            }
        }
        return out.str();
    }
    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        if (data.empty()) return nullptr;
        istringstream in(data);
        queue<TreeNode*> q;
        string val;
        in >> val;
        TreeNode *res = new TreeNode(stoi(val)), *cur = res;
        q.push(cur);
        while (!q.empty()) {
            TreeNode *t = q.front(); q.pop();
            if (!(in >> val)) break;
            if (val != "#") {
                cur = new TreeNode(stoi(val));
                q.push(cur);
                t->left = cur;
            }
            if (!(in >> val)) break;
            if (val != "#") {
                cur = new TreeNode(stoi(val));
                q.push(cur);
                t->right = cur;
            }
        }
        return res;
    }
};

參考資料: