返回题库

二叉树的序列化与反序列化

Serialize and Deserialize Binary Tree

专题
Algorithmic Programming / 算法编程
难度
L4
来源
Citadel

题目详情

问题:二叉树的序列化与反序列化

考察:树、递归

来源:Citadel

链接:https://www.jointaro.com/interviews/questions/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.

Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

 

Example 1:

Input: root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]

Example 2:

Input: root = []
Output: []

 

Constraints:

  • The number of nodes in the tree is in the range [0, 104].
  • -1000 <= Node.val <= 1000
解析

思路:用前序遍历序列化节点值,并用特殊标记表示空节点。反序列化时按同样前序顺序递归读取,遇到空标记返回 null。

复杂度:序列化和反序列化都是 O(n),空间 O(n)。