zoukankan      html  css  js  c++  java
  • [LintCode] Binary Tree Serialization

    Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.

    There is no limit of how you deserialize or serialize a binary tree, you only need to make sure you can serialize a binary tree to a string and deserialize this string to the original structure.

    Example

    An example of testdata: Binary tree {3,9,20,#,#,15,7}, denote the following structure:

      3
     / 
    9  20
      /  
     15   7
    

    Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.

    You can use other method to do serializaiton and deserialization.

    基本思路:

    利用queue层次遍历整棵树。对每次出队的结点,如果它是一个空结点,则再string后加入标记‘#’。如果它不是一个空节点,则把它的val加入到string中(如果string当前以一个非空结点结尾,我们加入一个’_'间隔),然后把这个结点的两个孩子入队(空节点也入队一次)。

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    
    class Solution {
    private:
        static const char nullNode = '#';
        static const char nodeSpliter = '_';
        
        inline string int2str(int val){
            stringstream strStream;
            strStream << val;
            return strStream.str();
        }
        
        inline int str2int(string str){
            return atoi(str.c_str());
        }
           
        inline void encode(string &str, TreeNode *node){
            if(node == NULL) {
                str += nullNode;
                return;
            }
            
            if(str == "" || str.back() == nullNode)
                str += int2str(node->val);
            else
                str += nodeSpliter + int2str(node->val);
        }
        
        vector<string> splitStr(string &str){
            vector<string> result;
            if(str == "") return result;
            int start = 0, end = 0, n = str.size();
            while(true){
                while(start < n && str[start] == nodeSpliter) ++start;
                if(start >= n) break;
                
                end = start + 1;
                if(str[start] != nullNode){
                    while(end < n && str[end] != nullNode && str[end] != nodeSpliter) 
                        ++end;
                }
                result.push_back(str.substr(start, end - start));
                start = end;
            }
            return result;
        }
        
    public:
        /**
         * This method will be invoked first, you should design your own algorithm 
         * to serialize a binary tree which denote by a root node to a string which
         * can be easily deserialized by your own "deserialize" method later.
         */
        string serialize(TreeNode *root) {
           if(root == NULL) return "";
           
           string encodedStr = "";
           queue<TreeNode*> nodeQueue;
           nodeQueue.push(root);
           
           while(!nodeQueue.empty()){
                TreeNode *cur = nodeQueue.front();
                nodeQueue.pop();
                encode(encodedStr, cur);
                if(cur != NULL){
                    nodeQueue.push(cur->left);
                    nodeQueue.push(cur->right);
                }
           }       
           return encodedStr;
        }
    
        /**
         * This method will be invoked second, the argument data is what exactly
         * you serialized at method "serialize", that means the data is not given by
         * system, it's given by your own serialize method. So the format of data is
         * designed by yourself, and deserialize it here as you serialize it in 
         * "serialize" method.
         */
        TreeNode *deserialize(string data) {
            vector<string> splitRes = splitStr(data);
            if(splitRes.size() == 0) return NULL;
            
            TreeNode *root = new TreeNode(str2int(splitRes[0]));
            queue<TreeNode*> nodeQueue;
            nodeQueue.push(root);
            
            for(int i = 1;i < splitRes.size();i+=2){
                if(nodeQueue.empty()) return root;
                TreeNode *curNode = nodeQueue.front();
                nodeQueue.pop();
                //left son
                if(splitRes[i][0] == nullNode){
                    curNode->left = NULL;
                }else{
                    curNode->left = new TreeNode(str2int(splitRes[i]));
                    nodeQueue.push(curNode->left);
                }
                //right son
                if(splitRes[i + 1][0] == nullNode){
                    curNode->right = NULL;
                }else{
                    curNode->right = new TreeNode(str2int(splitRes[i + 1]));
                    nodeQueue.push(curNode->right);   
                }
            }
            
            return root;
        }
    };
  • 相关阅读:
    windows系统切换jdk,修改java_home无效情况
    Cannot instantiate interface org.springframework.context.ApplicationListener
    MySQL分组查询获取每个学生前n条分数记录(分组查询前n条记录)
    ASP.NET Web API 使用Swagger生成在线帮助测试文档,支持多个GET
    EF TO MYSQL 无法查询中文的解决方法
    HttpWebRequest post请求获取webservice void数据信息
    This implementation is not part of the Windows Platform FIPS validated cryptographic algorithms. 此实现不是 Windows 平台 FIPS 验证的加密算法的一部分 解决方案
    MySQL 5.7.13解压版安装记录 mysql无法启动教程
    C# udpclient 发送数据断网后自动连接的方法
    汽车XX网站秒杀抢购代码
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/4763983.html
Copyright © 2011-2022 走看看