zoukankan      html  css  js  c++  java
  • Serialize and Deserialize Binary Tree

    Serialize and Deserialize Binary Tree

    Total Accepted: 6782 Total Submissions: 27834 Difficulty: Medium

    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.

    /**
     * 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 res;
            if(!root){
                res+="#.";
                return res;
            }
            res += to_string(root->val)+".";
            res += serialize(root->left);
            res += serialize(root->right);
            return res;
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            return _deserialize(data);
        }
    private:
        TreeNode* _deserialize(string& data) {
            int potpos = data.find_first_of('.',0);
        
            string num = data.substr(0,potpos);
            data.erase(0,potpos+1);
            
            if(num == "#") {
                return NULL;
            }   
            
            TreeNode* root = new TreeNode(atoi(num.c_str()));
            root->left = _deserialize(data);
            root->right = _deserialize(data);
            
            return root;
        }
    };
    
    // Your Codec object will be instantiated and called as such:
    // Codec codec;
    // codec.deserialize(codec.serialize(root));

     漂亮的代码:

    /**
     * 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) {
            ostringstream oss;
            serialize(root,oss);
            return oss.str();
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            istringstream iss(data);
            return deserialize(iss);
        }
    private:
        void serialize(TreeNode* root,ostringstream& oss) {
            if(!root){
                oss<<"# ";    
                return;
            } 
            oss<< root->val << ' ';
            serialize(root->left,oss);
            serialize(root->right,oss);
        }
    
        // Decodes your encoded data to tree.
        TreeNode* deserialize(istringstream& iss) {
            string val;
            iss>>val;
            if(val=="#") return NULL;
            TreeNode* root = new TreeNode(stoi(val));
            root->left     = deserialize(iss);
            root->right    = deserialize(iss);
            return root;
        }
    };
  • 相关阅读:
    FastAPI(38)- 模拟一个跨域场景
    FastAPI(37)- Middleware 中间件
    Python
    Python
    FastAPI(35)- 依赖项中使用 yield + Context Manager 上下文管理器
    汇编 | CPU物理地址本质理解
    汇编 | DosBox初步接触的一些初始化设置(窗口大小 & 默认命令)
    汇编语言 第3版 王爽 检测点答案及详细解析 (更新中)
    JSP | Tomcat目录结构详解
    JSP常见错误以及解决方案
  • 原文地址:https://www.cnblogs.com/zengzy/p/5057019.html
Copyright © 2011-2022 走看看