zoukankan      html  css  js  c++  java
  • LeetCode 297. Serialize and Deserialize Binary Tree 二叉树的序列化与反序列化(C++/Java)

    题目:

    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.

    Example: 

    You may serialize the following tree:
    
        1
       / 
      2   3
         / 
        4   5
    
    as "[1,2,3,null,null,4,5]"
    

    Clarification: The above format is the same as how LeetCode 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.

    分析:

    给定一颗二叉树将其序列化,也就是转换成一个字符串,同时还需要有一个反序列化的函数用来将字符串还原成二叉树。

    采用前序遍历或者层次遍历都可以,注意的是LeetCode上要求,不要使用类的成员 / 全局 / 静态变量来存储状态,你的序列化和反序列化算法应该是无状态的。

    C++中可以将 string 对象作为流处理,也就是istringstream 和 ostringstream。

    程序:

    C++

    class Codec {
    public:
    
        // Encodes a tree to a single string.
        string serialize(TreeNode* root) {
            ostringstream out;
            serialize(root, out);
            return out.str();
        }
        void serialize(TreeNode* root, ostringstream& out){
            if(root != nullptr){
                out << root->val << ' ';
                serialize(root->left, out);
                serialize(root->right, out);
            }
            else{
                out << "# ";
            }
        }
        // Decodes your encoded data to tree.
        TreeNode* deserialize(string data) {
            istringstream in(data);
            return deserialize(in);
        }
        TreeNode* deserialize(istringstream& in){
            string val;
            in >> val;
            if(val == "#"){
                return nullptr;
            }
            TreeNode* root = new TreeNode(stoi(val));
            root->left = deserialize(in);
            root->right = deserialize(in);
            return root;
        }
    };

    Java

    public class Codec {
    
        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            if(root == null)
                return "";
            StringBuilder str = new StringBuilder();
            serialize(root, str);
            return str.toString();
        }
        public void serialize(TreeNode root, StringBuilder str){
            if(root == null){
                str.append("#,"); 
                return;
            }
            str.append(root.val + ",");
            serialize(root.left, str);
            serialize(root.right, str);
        }
        
        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            if(data == "" || data == null)
                return null;
            String[] strs = data.split(",");
            LinkedList<String> l = new LinkedList<>(Arrays.asList(strs));
            return deserialize(l);
        }
        public TreeNode deserialize(LinkedList<String> list) {
            if(list.getFirst().equals("#")){
                list.removeFirst();
                return null;
            }
            TreeNode root = new TreeNode(Integer.parseInt(list.getFirst()));
            list.removeFirst();
            root.left = deserialize(list);
            root.right = deserialize(list);
            return root; 
        }
        
    }
  • 相关阅读:
    std thread
    windows更新包发布地址
    How to set up logging level for Spark application in IntelliJ IDEA?
    spark 错误 How to set heap size in spark within the Eclipse environment?
    hadoop 常用命令
    windows 安装hadoop 3.2.1
    windows JAVA_HOME 路径有空格,执行软连接
    day01MyBatisPlus条件构造器(04)
    day01MyBatisPlus的CRUD 接口(03)
    day01MyBatisPlus入门(02)
  • 原文地址:https://www.cnblogs.com/silentteller/p/12289545.html
Copyright © 2011-2022 走看看