前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode 297:二叉树的序列化与反序列化 Serialize and Deserialize Binary Tree

LeetCode 297:二叉树的序列化与反序列化 Serialize and Deserialize Binary Tree

作者头像
爱写bug
发布2020-03-12 18:47:54
6200
发布2020-03-12 18:47:54
举报
文章被收录于专栏:爱写Bug爱写Bug

序列化是将一个数据结构或者对象转换为连续的比特位的操作,进而可以将转换后的数据存储在一个文件或者内存中,同时也可以通过网络传输到另一个计算机环境,采取相反方式重构得到原数据。

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.

示例:

代码语言:javascript
复制
你可以将以下二叉树:

    1
   / \
  2   3
     / \
    4   5

序列化为 "[1,2,3,null,null,4,5]"

提示: 这与 LeetCode 目前使用的方式一致,详情请参阅 LeetCode 序列化二叉树的格式。你并非必须采取这种方式,你也可以采用其他的方法解决这个问题。

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 中的难度为最高级别 困难,但是实际体验真的很简单,主要考的还是二叉数的遍历。该题的序列化和反序列化各需一个前序遍历,真的非常简单。

Java:

代码语言:javascript
复制
public class Codec {

    public String serialize(TreeNode root) {
        return serializeHelper(root, "");
    }

    private String serializeHelper(TreeNode root, String str) {
        // 基线条件:遇到 null 时构造 “null” 字符串
        if (root == null)
            return str + "null,";
        // 构造返回字符串 str
        str += String.valueOf(root.val) + ",";
        str = serializeHelper(root.left, str);
        str = serializeHelper(root.right, str);
        return str;
    }

    public TreeNode deserialize(String data) {
        String[] data_array = data.split(",");
        // 根据前序遍历的结果逆向构造二叉树时,因为要从左到右操作前序遍历结果,所以使用队列更适合
        Queue<String> list = new LinkedList<>(Arrays.asList(data_array));
        return deserializeHelper(list);
    }

    private TreeNode deserializeHelper(Queue<String> queue) {
        if (queue.peek().equals("null")) {
            queue.poll();
            return null;
        }
        TreeNode root = new TreeNode(Integer.valueOf(queue.poll()));
        root.left = deserializeHelper(queue);
        root.right = deserializeHelper(queue);
        return root;
    }
}

Python

代码语言:javascript
复制
class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.

        :type root: TreeNode
        :rtype: str
        """
        def helper(root, string):
            if not root:
                string += "None,"
            else:
                string += str(root.val)+","
                string = helper(root.left, string)
                string = helper(root.right, string)
            return string
        return helper(root, '')

    def deserialize(self, data):
        """Decodes your encoded data to tree.

        :type data: str
        :rtype: TreeNode
        """
        def helper(l: list):
            if(l[0] == "None"):
                l.pop(0)
                return None
            root = TreeNode(l.pop(0))
            root.left = helper(l)
            root.right = helper(l)
            return root

        data_list = data.split(',')
        root = helper(data_list)
        return root
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-03-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 爱写Bug 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 解题思路:
  • Java:
  • Python
相关产品与服务
文件存储
文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档