[leetcode297]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.

Credits:
Special thanks to  @Louis1992  for adding this problem and creating all test cases.

算法:

serialize算法很简单,利用广度优先逐层遍历节点,遇到None就进行下一次循环。遍历的同时,利用容器收集节点值的信息。最后用join方法拼接字符串。
具体而言,上图中的二叉树的遍历队列应该是:
[1]
[2,3]
[3,null,null]
[null,null,4,5]
[null,4,5]
[4,5]
[5,null,null]
[null,null,null,null]
[null,null,null]
[null,null]
[null]
[]
Deserialize算法也很简单。先用split将字符串转为节点列表。然后使用双指针,parent_idx指向当前父节点,sub_idx指向父节点的左子树。 逐次迭代,每次parent_idx += 1,sub_idx += 2,遇到None,parent_idx自增,而sub_idx 保持不变。

代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from collections import deque
class Codec(object):

    def serialize(self, root):
        """Encodes a tree to a single string.
        
        :type root: TreeNode
        :rtype: str
        """
        container = []
        que = deque([root])
        while que:
            cur = que.popleft()
            if cur is None:
                container.append('null')
                continue
            else:
                container.append(str(cur.val))
                que.append(cur.left)
                que.append(cur.right)

        return ",".join(container)
        

    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        if not data:
            return None
        container = [TreeNode(int(ele)) if ele != 'null' else None for ele in data.split(',')]
        parent_idx = 0
        sub_idx = 1
        # root = None
        while sub_idx+1 < len(container) and parent_idx < len(container):
            parent = container[parent_idx]
            if parent is None:
                parent_idx += 1
                continue
            else:
                parent.left = container[sub_idx]
                parent.right = container[sub_idx+1]
                parent_idx += 1
                sub_idx += 2
        return container[0]


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








全部评论

相关推荐

03-11 18:00
辽宁大学 安卓
这怎么还花钱买上了.....
不愿吃饼的变色龙很感性:没事,我不是目标院校,练花钱的机会都没有
点赞 评论 收藏
分享
01-23 14:54
同济大学 Java
热爱敲代码的程序媛:给你提几点【专业技能】这个模块里面可优化的地方:1.【具备JVM调优经验】可以去b站上搜一下JVM调优的视频,估计一两个小时凭你的学习能力就能掌握JVM调优的实践方面的技能。2.【MySql优化】MySql这一栏,你去b站或者找个博客看看MySql优化,学一下,如果你本身比较熟悉MySql语句的话,那基本半天时间凭你的学习能力MySql语句优化方面的技能你也能掌握个差不多。以上1,2两点主要是因为我看你专业技能大部分都说的是偏理论,没有写应用。再就是最后,你结合你的项目,想一想你的项目中哪些sql语句是可以用MySql优化的,到时候你面试的时候也好结合着说一下。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务