c_cpp 297.序列化和反序列化二叉树 - 难度硬 - 2018.9.14

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 297.序列化和反序列化二叉树 - 难度硬 - 2018.9.14相关的知识,希望对你有一定的参考价值。

/**
 * 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 re;
        if (root == NULL) re = "#,";
        else re = to_string(root->val) + ',' + serialize(root->left) + serialize(root->right);
        return re;
    }
    
    TreeNode *deserialize(queue<string>& dQ) {
        if (dQ.size() <= 0) return NULL;
        string chh = dQ.front();
        dQ.pop();
        TreeNode *node;
        if (chh == "#") {
            return NULL;
        } else {
            node = new TreeNode(atoi(chh.c_str()));
            node->left = deserialize(dQ);
            node->right = deserialize(dQ);
        }
        return node;
    }
    
    queue<string> splitStr(string data) {
        queue<string> re;
        int len = strlen(data.c_str());
        if (len <= 0) 
            return re;
        int lInex = 0;
        int rIndex = 0;
        while(rIndex < len) {
            if (data[rIndex] == ','
               && rIndex != lInex) {
                string tmpStr = data.substr(lInex, rIndex-lInex);
                re.push(tmpStr);
                lInex = rIndex+1;
            }
            rIndex++;
        }
        return re;
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        queue<string> dVec = splitStr(data);
        return deserialize(dVec);
    }
};

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

以上是关于c_cpp 297.序列化和反序列化二叉树 - 难度硬 - 2018.9.14的主要内容,如果未能解决你的问题,请参考以下文章

java 297.序列化和反序列化二叉树(#1 BFS).java

java 297.序列化和反序列化二叉树(#1 BFS).java

java 297.序列化和反序列化二叉树(#1 BFS).java

java 297.序列化和反序列化二叉树(#1 BFS).java

java 297.序列化和反序列化二叉树(#1 BFS).java

java 297.序列化和反序列化二叉树(#1 BFS).java