问题描述:
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.
For example, you may serialize the following tree
1 / \ 2 3 / \ 4 5as
"[1,2,3,null,null,4,5]"
, just the same as how LeetCode OJ serializes a binary tree . You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.
Credits:Special thanks to @Louis1992 for adding this problem and creating all test cases.
算法:
serialize算法很简单,利用广度优先逐层遍历节点,遇到None就进行下一次循环。遍历的同时,利用容器收集节点值的信息。最后用join方法拼接字符串。
具体而言,上图中的二叉树的遍历队列应该是:
[1]
[2,3]
[3,null,null]
[null,null,4,5]
[null,4,5]
[4,5]
[5,null,null]
[null,null,null,null]
[null,null,null]
[null,null]
[null]
[]
Deserialize算法也很简单。先用split将字符串转为节点列表。然后使用双指针,parent_idx指向当前父节点,sub_idx指向父节点的左子树。 逐次迭代,每次parent_idx += 1,sub_idx += 2,遇到None,parent_idx自增,而sub_idx 保持不变。
代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Codec(object):
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
container = []
que = deque([root])
while que:
cur = que.popleft()
if cur is None:
container.append('null')
continue
else:
container.append(str(cur.val))
que.append(cur.left)
que.append(cur.right)
return ",".join(container)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if not data:
return None
container = [TreeNode(int(ele)) if ele != 'null' else None for ele in data.split(',')]
parent_idx = 0
sub_idx = 1
# root = None
while sub_idx+1 < len(container) and parent_idx < len(container):
parent = container[parent_idx]
if parent is None:
parent_idx += 1
continue
else:
parent.left = container[sub_idx]
parent.right = container[sub_idx+1]
parent_idx += 1
sub_idx += 2
return container[0]
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))