题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
序列化时:“#”代表空,“!”代表该节点结束。采用先序遍历方式序列化。
反序列化:按照先序方式
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def Serialize(self, root):
# write code here
if root is None:
return "#"
return str(root.val)+"!"+self.Serialize(root.left)+"!"+self.Serialize(root.right)
def Deserialize(self, s):
# write code here
l = s.split("!")
def dg(l):
root = None
if len(l)<=0:
return
pop = l.pop(0)
if pop != "#":
root = TreeNode(int(pop))
root.left = dg(l)
root.right = dg(l)
return root
return dg(l)