请实现两个函数,分别用来序列化和反序列化二叉树。
示例:
你可以将以下二叉树:
1
/ \
2 3
/ \
4 5
序列化为 "[1,2,3,null,null,4,5]"
注意:本题与主站 297 题相同:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
前序遍历
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
res=[]
stack=[root]
while stack:
node=stack.pop()
if node:
res.append(node.val)
stack.append(node.right)
stack.append(node.left)
else:
res.append(None)
return res
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
self.index=0
def dfs(data):
if data[self.index]==None:
self.index+=1
return
root=TreeNode(data[self.index])
self.index+=1
root.left=dfs(data)
root.right=dfs(data)
return root
return dfs(data)