class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
res = ‘‘
if not root:
return res
node_pool = [root]
res = str(root.val)
while node_pool:
tmp = []
for node in node_pool:
if not node.left:
res += ‘,‘ + ‘null‘
else:
res += ‘,‘ + str(node.left.val)
tmp.append(node.left)
if not node.right:
res += ‘,‘ + ‘null‘
else:
res += ‘,‘ + str(node.right.val)
tmp.append(node.right)
node_pool = tmp
print(res)
return res
def deserialize(self, data):
if not data:
return None
str_set = data.split(‘,‘)
res = TreeNode(int(str_set[0]))
node_pool = [res]
ptr = 1
nums = 2
while ptr < len(str_set):
child_pool = []
child_set = str_set[ptr:ptr + nums]
for i, node in enumerate(node_pool):
if child_set[2 * i] != ‘null‘:
node.left = TreeNode(int(child_set[2 * i]))
child_pool.append(node.left)
if child_set[2 * i + 1] != ‘null‘:
node.right = TreeNode(int(child_set[2 * i + 1]))
child_pool.append(node.right)
ptr += nums
nums = 2 * len(child_pool)
node_pool = child_pool
return res
原文:https://www.cnblogs.com/2014slx/p/13149467.html