# 297. 二叉树的序列化与反序列化

## 297. 二叉树的序列化与反序列化

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

class Codec:

def serialize(self, root):
"""Encodes a tree to a single string.

:type root: TreeNode
:rtype: str
"""
# 使用队列操作序列化二叉树，数据结构使用collections中的双端队列(参考BFS优先搜索)
if not root:
return "[]"
queue = collections.deque()
# 将根节点入队
queue.append(root)
# 用于存储序列化结果的列表
res = []
while queue:
node = queue.popleft()
if node:
res.append(str(node.val))
# 将当前节点的左右子节点入队
queue.append(node.left)
queue.append(node.right)
else:
res.append("null")
return '[' + ','.join(res) + ']'

def deserialize(self, data):
"""Decodes your encoded data to tree.

:type data: str
:rtype: TreeNode
"""
# 反序列化二叉树，数据结构同样可以使用双端队列进行操作
if data == "[]":
return
# 1和-1的切片索引用来过滤掉'[' ']'两个字符，
# i可看做指针或者偏移量计数器，初始化为1，即elements数组中的第二个节点
elements, i = data[1:-1].split(','), 1
# 构建根节点
root = TreeNode(int(elements[0]))
queue = collections.deque()
queue.append(root)
while queue:
# 队列中的元素出队，用于构建该元素的左右子树
node = queue.popleft()
# 构建左子树
if elements[i] != "null":
node.left = TreeNode(int(elements[i]))
queue.append(node.left)
# 偏移量+1，指向下一个元素
i += 1
# 构建右子树
if elements[i] != "null":
node.right = TreeNode(int(elements[i]))
queue.append(node.right)
# 偏移量+1，指向下一个元素
i += 1
return root

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))


https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof/solution/mian-shi-ti-37-xu-lie-hua-er-cha-shu-ceng-xu-bian-/

11-05 135
03-01 77
07-22 193
08-28 208
12-05 836
07-11 5万+
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客