leetcode刷题四十九

Posted hhh江月

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode刷题四十九相关的知识,希望对你有一定的参考价值。

leetcode刷题四十九

题目叙述

https://leetcode.cn/problems/serialize-and-deserialize-bst/

序列化是将数据结构或对象转换为一系列位的过程,以便它可以存储在文件或内存缓冲区中,或通过网络连接链路传输,以便稍后在同一个或另一个计算机环境中重建。

设计一个算法来序列化和反序列化 二叉搜索树 。 对序列化/反序列化算法的工作方式没有限制。 您只需确保二叉搜索树可以序列化为字符串,并且可以将该字符串反序列化为最初的二叉搜索树。

编码的字符串应尽可能紧凑。

题目解答

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Codec:

    # def serialize(self, root: TreeNode) -> str:
    #     """Encodes a tree to a single string.
    #     """
    #     L = []      
    #     def t(node): 
    #         if node.left:
    #             t(node.left)
    #         L.append(node.val)
    #         if node.right :
    #             t(node.right)
    #     if not root:
    #         pass
    #     else:
    #         t(root)
    #     return str(L)


    # def deserialize(self, data: str) -> TreeNode:
    #     """Decodes your encoded data to tree.
    #     """
    #     list0 = data.split(',')
    #     return None
    #     class Codec:

    def serialize(self, root: TreeNode) -> str:
        """Encodes a tree to a single string."""
        if not root:
            return "[]"

        s = deque([root])
        sb = "["
        cnt = 1

        while 1:
            cur = s.popleft()
            if not cur:
                sb += "null"
            else:
                cnt -= 1
                sb += str(cur.val)
                s.append(cur.left)
                s.append(cur.right)
                if cur.left:
                    cnt += 1
                if cur.right:
                    cnt += 1
            if cnt == 0 or not s:
                return sb + ']'
            sb += ','

    def deserialize(self, data: str) -> TreeNode:
        """Decodes your encoded data to tree."""
        if len(data) <= 2:
            return None

        nums = data[1:len(data) - 1].split(',')
        n, p = len(nums), 1
        if n == 1 and 'null' in nums[0]:
            return None
        root = TreeNode(int(nums[0]))
        s = deque([root])
        while p < n:
            cur = s.popleft()
            if "null" not in nums[p]:
                cur.left = TreeNode(int(nums[p]))
                s.append(cur.left)
            p += 1
            if p < n and "null" not in nums[p]:
                cur.right = TreeNode(int(nums[p]))
                s.append(cur.right)
            p += 1
        return root


        

# Your Codec object will be instantiated and called as such:
# Your Codec object will be instantiated and called as such:
# ser = Codec()
# deser = Codec()
# tree = ser.serialize(root)
# ans = deser.deserialize(tree)
# return ans


题目运行

以上是关于leetcode刷题四十九的主要内容,如果未能解决你的问题,请参考以下文章

leetcode刷题四十七

leetcode刷题四十七

leetcode刷题四十三

leetcode刷题四十三

leetcode刷题四十四

leetcode刷题四十四