297. Serialize and Deserialize Binary Tree

来源:互联网 发布:lol免费充点卷软件. 编辑:程序博客网 时间:2024/06/03 22:04

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.

/** * 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.    int depth(TreeNode *root){        if(root == NULL){            return 0;        }        int l = 1 + depth(root->left);        int r = 1 + depth(root->right);        return l>r?l:r;    }    string creatStr(TreeNode* root) {        string str;        queue<TreeNode *> qu;        int depthTree = depth(root);        if(root == NULL){            return str;        }        str += to_string(root->val);        if(!root->left&&!root->right){            return str;        }        qu.push(root);        while(!qu.empty()){            int level = qu.size();            depthTree--;            for(int i = 0;i<level;i++){                TreeNode* rootNode = qu.front();                qu.pop();                if(rootNode->left){                    str += ",";                   str += to_string(rootNode->left->val);                   qu.push(rootNode->left);                }else{                   if(depthTree > 0){                       str += ",";                       str += "null";                     }                                 }                if(rootNode->right){                   str += ",";                    str += to_string(rootNode->right->val);                   qu.push(rootNode->right);                }else{                   if(depthTree > 0){                       str += ",";                       str += "null";                    }                }            }        }        return str;    }    string serialize(TreeNode* root) {        string str = creatStr(root);        if(str != ""){           str = "[" + str + "]";         }        return str;    }    TreeNode * creatTree(vector<string> nodeStr) {        TreeNode * root = NULL;        TreeNode * rootNode = NULL;        if(nodeStr.size() == 0){            return NULL;        }        queue<TreeNode *> qu;        int i = 0;           if(nodeStr[i] != "null"){            TreeNode * newNode = (TreeNode *)malloc(sizeof(TreeNode));            newNode->val = atoi(nodeStr[i].c_str());            newNode->left = NULL;            newNode->right = NULL;            root = newNode;            qu.push(newNode);        }else{            return NULL;        }        i++;        while(i<nodeStr.size()){             rootNode = qu.front();             if(nodeStr[i] == "null"){                 rootNode->left = NULL;             }else{                 TreeNode * newNode = (TreeNode *)malloc(sizeof(TreeNode));                 newNode->val = atoi(nodeStr[i].c_str());                 //cout<<newNode->val<<endl;                 newNode->left = NULL;                 newNode->right = NULL;                 rootNode->left = newNode;                 qu.push(newNode);             }             i++;             if(nodeStr[i] == "null"){                 rootNode->right = NULL;             }else{                 TreeNode * newNode = (TreeNode *)malloc(sizeof(TreeNode));                 newNode->val = atoi(nodeStr[i].c_str());                 //cout<<newNode->val<<endl;                 newNode->left = NULL;                 newNode->right = NULL;                 rootNode->right = newNode;                 qu.push(newNode);             }             qu.pop();             i++;        }        return root;    }    // Decodes your encoded data to tree.    TreeNode* deserialize(string data) {        vector<string> nodeStr;        const char * start = NULL;        if(data == ""){            return NULL;        }        const char * p = data.c_str();        //cout<<data<<endl;        p++;/*skip '['*/        while((*p)!=']'&&(*p)!='\0'){            start = p;            while((*p)!=','&&(*p)!=']'){                p++;            }            nodeStr.push_back(data.substr(start-data.c_str(),p-start));            p++;                       }        int len = nodeStr.size();        return creatTree(nodeStr);    }};// Your Codec object will be instantiated and called as such:// Codec codec;// codec.deserialize(codec.serialize(root));