1. 程式人生 > >Leetcode:297. Serialize and Deserialize Binary Tree

Leetcode:297. 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.

大意就是將一個二叉樹序列化為一個string和將string反序列化之後,使之和原二叉樹一樣。

這裡關鍵是如何去根據二叉樹構造string,也就是按什麼樣的遍歷方法來構造string。

直觀上容易接受的是按照層序遍歷來構造,好處是序列化的時候很容易,使用一個佇列即可實現,但難的是反序列化的時候,不好將二叉樹重新構造出來。

後來決定根據dfs的順序,也就是先序遍歷來構造string,利用遞迴的特性,序列化和反序列化都是比較容易的。

class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string res;
        stringstream ss;
        serializeDFS(root, ss);
        ss >> res;
        return res;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        int cnt = 0;
        return deserializeDFS(data, cnt);
    }
private:
    void serializeDFS(TreeNode* root, stringstream &ss) {
        if(!root) {ss << "N,"; return;}
        ss << root->val;
        ss << ",";
        serializeDFS(root->left, ss);
        serializeDFS(root->right, ss);
    }
    
    TreeNode* deserializeDFS(const string& data, int& cnt) {
        if(cnt >= data.size()) return nullptr;
        if(data[cnt] == 'N') {
            cnt += 2;
            return nullptr;
        }
        int num = getNum(data, cnt);
        auto root = new TreeNode(num);
        root->left = deserializeDFS(data, cnt);
        root->right = deserializeDFS(data, cnt);
        return root;
    }
    
    int getNum(const string& data, int& cnt) {
        int res = 0;
        bool negFlag = false;
        if(data[cnt] == '-') {
            negFlag = true;
            ++cnt;
        }
        while(data[cnt] != ',') {
            res = res*10 + (data[cnt]-'0');
            ++cnt;
        }
        ++cnt;
        if(negFlag) res *= (-1);
        return res;
    }
};