這個題難度其實不大,
利用深度優先遍歷構建字符串,同時也利用深度遍歷返回樹。
class Codec:
def __init__(self):
self.idx = 0
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
p = root
stack, nodes = [], []
while stack or p:
if p:
nodes.append(str(p.val))
stack.append(p)
p = p.left
else:
nodes.append('None')
p = stack.pop()
p = p.right
nodes.append('None')
return ' '.join(nodes)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
list1 = data.split(' ')
self.idx = 0
return self.constructTree(list1)
def constructTree(self, list1):
if self.idx >= len(list1) or list1[self.idx] == 'None':
self.idx += 1
return None
val = int(list1[self.idx])
self.idx += 1
node = TreeNode(val)
node.left = self.constructTree(list1)
node.right = self.constructTree(list1)
return node