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;
        }
    };
  • 相关阅读:
    一个经典的页面布局
    巧避new的一个原型设计模式
    讲解关于javascript的继承
    根据指定日期 算出该周的一周日期
    原型实现的一个观察者模式
    减少类之间的耦合性
    Android 代码下载
    (转)open gl 实例 demo vs2005 环境
    Tile editor 快捷键
    这是第一篇博客~
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/4763983.html
Copyright © 2011-2022 走看看