LeetCode 449. Serialize and Deserialize BST - 二叉搜索树(Binary Search Tree)系列题10

Serialization is 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 search tree. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.

The encoded string should be as compact as possible.

Example 1:

Input: root = [2,1,3]
Output: [2,1,3]

Example 2:

Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • 0 <= Node.val <= 104
  • The input tree is guaranteed to be a binary search tree.

题目要求对二叉搜索树进行序列化和去序列化。所谓序列化就是把二叉搜索树转化成一个位序列,以致可以把它存在一个文件或内存里,或者通过网络传输。去序列化就是在接收端接收到二叉搜索树的序列,并把该序列恢复成原来的二叉搜索树。

我们所熟悉的二叉搜索树的遍历算法其实就是把一棵二叉搜索树转换成一个数组,其实就是一个序列化过程中。把遍历后的数组用一个分隔符把每个节点分隔开放进一个字符串里就可以对其保存或传输了。在接收端只要知道是序列是用哪种遍历方法的就可以进行去序列化了。最方便的就是前序遍历,因为对于任意一个子树序列,序列的第一个数就是子树的根节点,序列剩余部分可以分成小于根节点值的前面部分和大于根节点值的后面部分,两部分分别是左子树和右子树。

255. Verify Preorder Sequence in Binary Search Tree中我们知道如何验证一个前序遍历序列中每个节点是否属于二叉搜索树的节点从而知道是否为一棵有效二叉搜索树。换句话说,如果知道了序列肯定是一棵二叉搜索树的前序遍历序列,那用同样的方法就可以知道序列中的节点是为其父节点的左子节点还是右子节点。

# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Codec:

    def serialize(self, root: Optional[TreeNode]) -> str:
        """Encodes a tree to a single string.
        """
        def preorder(node):
            if not node:
                return []
            return [node.val] + preorder(node.left) + preorder(node.right)
        
        return ' '.join(map(str, preorder(root)))

    def deserialize(self, data: str) -> Optional[TreeNode]:
        """Decodes your encoded data to tree.
        """
        arr = [int(i) for i in data.split(' ') if i]
        
        i = 0
        def helper(low, high):
            nonlocal i
            if i == len(arr) or arr[i] < low or arr[i] > high:
                return None
            
            val = arr[i]
            root = TreeNode(val)
            i += 1
            root.left = helper(low, val)
            root.right = helper(val, high)
            return root
        
        return helper(-sys.maxsize, sys.maxsize)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值