首页 > 其他 > 详细

leetcode-297-二叉树的序列化和反序列化

时间:2019-10-16 22:12:08      阅读:101      评论:0      收藏:0      [点我收藏+]

题目描述:

技术分享图片

 

方法一:深度优先(官方题解) 

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.
        
        :type root: TreeNode
        :rtype: str
        """
        def rserialize(root, string):
            """ a recursive helper function for the serialize() function."""
            # check base case
            if root is None:
                string += None,
            else:
                string += str(root.val) + ,
                string = rserialize(root.left, string)
                string = rserialize(root.right, string)
            return string
        return rserialize(root,"")

    def deserialize(self, data):
        """Decodes your encoded data to tree.
        
        :type data: str
        :rtype: TreeNode
        """
        if not data:
            return
        def rdeserialize(l):
            """ a recursive helper function for deserialization."""
            if l[0] == None:
                l.pop(0)
                return None
                
            root = TreeNode(l[0])
            l.pop(0)
            root.left = rdeserialize(l)
            root.right = rdeserialize(l)
            return root

        data_list = data.split(,)
        root = rdeserialize(data_list)
        return root

 

leetcode-297-二叉树的序列化和反序列化

原文:https://www.cnblogs.com/oldby/p/11688260.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!