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;
        }
    };
  • 相关阅读:
    AgularJS中Unknown provider: $routeProvider解决方案
    AngularJS依赖注入
    下面是Webstorm的一些常用快捷键:
    加载多张图片,判断加载完成状态
    JS控制图片显示的大小(图片等比例缩放)
    JS中两个重要的方法 call & apply 学习
    如何用微软雅黑显示自己网页的字体
    Dev-C++的一些使用技巧快捷键
    C C语言中 *.c和*.h文件的区别!
    HTML <!--...--> 注释 、CSS/JS //注释 和 /*.....*/ 注释
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/4763983.html
Copyright © 2011-2022 走看看