题目:
请实现两个函数,分别用来序列化和反序列化二叉树。
思路如下图:
代码实现如下:
#序列化
def Serialize(self, root):
if not root:
return '#'
return str(root.val) +',' + self.Serialize(root.left) +','+ self.Serialize(root.right)
#反序列化
def Deserialize(self, s):
list = s.split(',')
return self.deserializeTree(list)
def deserializeTree(self, list):
if len(list)<=0:
return None
val = list.pop(0)
root = None
if val != '#':
root = TreeNode(int(val))
root.left = self.deserializeTree(list)
root.right = self.deserializeTree(list)
return root