`

Serialize and Deserialize Binary Tree

阅读更多
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.

序列化一个二叉树,然后再根据二叉树的序列得到二叉树。我们可以用层序遍历(队列)得到一棵树的序列化,空的节点用n表示,然后在根据序列化生成二叉树,同样借助队列。代码如下:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root == null) return "";
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        StringBuilder sb = new StringBuilder();
        queue.offer(root);
        while(!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if(node == null) {
                sb.append("n ");
            } else {
                sb.append(node.val + " ");
                queue.offer(node.left);
                queue.offer(node.right);
            }
        }
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data == "") return null;
        String[] string = data.split("\\s");
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        TreeNode root = new TreeNode(Integer.parseInt(string[0]));
        queue.offer(root);
        for(int i = 1; i < string.length; i++) {
            TreeNode parent = queue.poll();
            if(!string[i].equals("n")) {
                 parent.left = new TreeNode(Integer.parseInt(string[i]));
                 queue.offer(parent.left);
            }
            if(++i < string.length && !string[i].equals("n")) {
                parent.right = new TreeNode(Integer.parseInt(string[i]));
                queue.offer(parent.right);
            }
        }
        return root;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));

我们还可以通过DFS得到一个序列,然后在生成二叉树。代码如下:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Codec {

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        if(root == null) return "";
        Stack<TreeNode> stack = new Stack<TreeNode>();
        StringBuilder sb = new StringBuilder();
        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode parent = stack.pop();
            if(parent == null) {
                sb.append("n ");
            } else {
                sb.append(parent.val + " ");
                stack.push(parent.right);
                stack.push(parent.left);
            }
        }
        System.out.println(sb.toString());
        return sb.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        if(data == "") return null;
        String[] string = data.split("\\s");
        int[] i = new int[1];
        return getNode(string, i);
    }
    //  1 2 n n 3 n n
    private TreeNode getNode(String[] string, int[] i) {
        if(i[0] >= string.length || string[i[0]].equals("n")) return null;
        TreeNode root = new TreeNode(Integer.parseInt(string[i[0]]));
        i[0]++;
        root.left = getNode(string, i);
        i[0]++;
        root.right = getNode(string, i);
        return root;
    }
}

// Your Codec object will be instantiated and called as such:
// Codec codec = new Codec();
// codec.deserialize(codec.serialize(root));
分享到:
评论

相关推荐

    Serialize and Deserialize Java 示例程序

    Serialize and Deserialize Java 示例程序。简单来讲,它的数据格式与json类似,但是在存储时对数字、多字节字符、数组等都做了很多优化,减少了无用的字符,二进制格式,也保证不用字符化带来额外的存储空间的增加...

    c语言-leetcode题解之0297-serialize-and-deserialize-binary-tree

    c c语言_leetcode题解之0297_serialize_and_deserialize_binary_tree

    2018年最新Google Onsite面经总结1

    Serialize and Deserialize Binary Tree、298. Binary Tree Longest Consecutive Sequence等。这类题目通常要求读者使用树的各种操作来解决问题,例如树的遍历、查找、插入等操作。 4. 图类题目 图类题目是...

    leetcode添加元素使和等于-leetcode:我的leetcode解决方案

    Deserialize Binary Tree Minimum Window Substring C++ STL中常见容器的时间复杂度 map, set, multimap, and multiset 上述四种容器采用红黑树实现,红黑树是平衡二叉树的一种。不同操作的时间复杂度近似为: 插入:O...

    serialize binary tree.pdf

    return 1 + Math.max(height(tree.leftChild()), height(tree.rightSibling())); } ``` #### 4. 序列化二叉树 序列化是指将数据结构或对象状态转换为可以存储或传输的形式的过程。对于二叉树来说,序列化可以帮助...

    LeetCode最全代码

    * [Binary Search Tree](https://github.com/kamyu104/LeetCode#binary-search-tree) * [Breadth-First Search](https://github.com/kamyu104/LeetCode#breadth-first-search) * [Depth-First Search]...

    C#序列化与反序列化(Serialize,Deserialize)实例详解

    本文实例讲述了C#序列化与反序列化(Serialize,Deserialize)实现方法。分享给大家供大家参考。具体分析如下: 如果要保存运行程序过程的数据要么保存到数据库中,要么新建一个普通的文件,然后把数据保存进去.但是这...

    Android代码-yamlbeans

    YamlBeans makes it easy to serialize and deserialize Java object graphs to and from YAML, a human-friendly data format. Replace XML and properties files with YAML for more expressive power (lists, ...

    Android代码-CacheUtilsLibrary

    This is a simple Android utils library to write any type of data into cache files and then read them later, using Gson to serialize and deserialize these data. 中文版请看这里。 Gradle compile '...

    The Modern C++ Challenge

    Serialize and deserialize JSON and XML data Perform encryption and signing to facilitate secure communication between parties Embed and use SQLite databases in your applications Use threads and ...

    TIA博途-序列化指令Serialize的具体使用方法示例.docx

    同时,`Deserialize`指令提供了反序列化功能,可以从BYTE数组中恢复原始的UDT或STRUCT数据,这样可以实现数据的完整生命周期管理,从创建、传输到解析。 为了更好地掌握这个功能,建议动手实践,尝试创建自己的UDT...

    form-serialize-and-calculate.html

    form-serialize-and-calculate.html

    opg:Rust OpenAPI 3.0文档生成器

    use serde :: {Serialize, Deserialize}; #[derive(Serialize, Deserialize, OpgModel)] #[serde(rename_all = "camelCase" )] #[opg( "Simple enum" )] enum SimpleEnum { Test, Another, Yay, } #[derive...

    .net Newtonsoft.Json 4.0 release

    you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects. LINQ to JSON allows you to easily ...

    :locked_with_key: 加密所有的 Serialize。

    Alice Bob+-----------------------------------+ +-----------------------------------+| #[derive(Serialize, Deserialize)] | | #[derive(Serialize, Deserialize)] || struct Message | | struct Message |+--...

    matlab开发-serialize

    在MATLAB中,`serialize`...正确使用`serialize`和`deserialize`,可以在各种复杂的MATLAB开发场景中提高效率和便利性。在实践中,要根据具体需求选择合适的数据序列化和反序列化策略,以确保数据的完整性和兼容性。

    Json.NET 6.0 R3 For.NET(2.0-4.5)

    Json.NET Json.NET is a popular ... you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects.

Global site tag (gtag.js) - Google Analytics