LeetCode 题解工作台

序列化和反序列化二叉搜索树

序列化是将数据结构或对象转换为一系列位的过程,以便它可以存储在文件或内存缓冲区中,或通过网络连接链路传输,以便稍后在同一个或另一个计算机环境中重建。 设计一个算法来序列化和反序列化 二叉搜索树 。 对序列化/反序列化算法的工作方式没有限制。 您只需确保二叉搜索树可以序列化为字符串,并且可以将该字符串…

category

7

题型

code_blocks

4

代码语言

hub

3

相关题

当前训练重点

中等 · 二分·树·traversal

bolt

答案摘要

题目给定的是二叉搜索树,我们知道二叉搜索树的中序遍历是有序的,而通过“先序遍历”和“中序遍历”可以唯一确定一棵二叉树,所以我们可以通过先序遍历的结果和中序遍历的结果来唯一确定一棵二叉搜索树。 在 `serialize` 方法中,我们使用先序遍历的方式将二叉搜索树序列化为空格分隔的字符串,然后在 `deserialize` 方法中,我们将字符串按空格分割为数组,然后使用递归的方式来构建二叉搜索树。递…

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 二分·树·traversal 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

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

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

 

示例 1:

输入:root = [2,1,3]
输出:[2,1,3]

示例 2:

输入:root = []
输出:[]

 

提示:

  • 树中节点数范围是 [0, 104]
  • 0 <= Node.val <= 104
  • 题目数据 保证 输入的树是一棵二叉搜索树。
lightbulb

解题思路

方法一:先序遍历

题目给定的是二叉搜索树,我们知道二叉搜索树的中序遍历是有序的,而通过“先序遍历”和“中序遍历”可以唯一确定一棵二叉树,所以我们可以通过先序遍历的结果和中序遍历的结果来唯一确定一棵二叉搜索树。

serialize 方法中,我们使用先序遍历的方式将二叉搜索树序列化为空格分隔的字符串,然后在 deserialize 方法中,我们将字符串按空格分割为数组,然后使用递归的方式来构建二叉搜索树。递归函数为 dfs(mi,mx)dfs(mi, mx),表示当前节点的值必须在 [mi,mx][mi, mx] 之间,如果当前节点的值不在 [mi,mx][mi, mx] 之间,则说明这个节点不是当前递归树的节点,返回 None

时间复杂度 O(n)O(n),空间复杂度 O(n)O(n)。其中 nn 是二叉搜索树的节点数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 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: Optional[TreeNode]) -> str:
        """Encodes a tree to a single string."""

        def dfs(root: Optional[TreeNode]):
            if root is None:
                return
            nums.append(root.val)
            dfs(root.left)
            dfs(root.right)

        nums = []
        dfs(root)
        return " ".join(map(str, nums))

    def deserialize(self, data: str) -> Optional[TreeNode]:
        """Decodes your encoded data to tree."""

        def dfs(mi: int, mx: int) -> Optional[TreeNode]:
            nonlocal i
            if i == len(nums) or not mi <= nums[i] <= mx:
                return None
            x = nums[i]
            root = TreeNode(x)
            i += 1
            root.left = dfs(mi, x)
            root.right = dfs(x, mx)
            return root

        nums = list(map(int, data.split()))
        i = 0
        return dfs(-inf, inf)


# 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
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for the candidate's understanding of tree traversal methods and how they relate to serialization.

  • question_mark

    Evaluate the ability to choose the most space-efficient approach based on the tree's size and structure.

  • question_mark

    Assess the candidate's attention to detail in handling edge cases, such as empty trees or trees with a large number of nodes.

warning

常见陷阱

外企场景
  • error

    Over-complicating the algorithm by not considering simple traversal techniques like pre-order or BFS.

  • error

    Failing to account for null nodes during serialization, leading to incorrect deserialization.

  • error

    Not optimizing for space in scenarios with large trees, resulting in excessive memory usage.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Using a post-order or in-order traversal for serialization instead of pre-order.

  • arrow_right_alt

    Implementing the solution iteratively without recursion.

  • arrow_right_alt

    Optimizing the solution for trees with high depth and low width.

help

常见问题

外企场景

序列化和反序列化二叉搜索树题解:二分·树·traversal | LeetCode #449 中等