题目描述
请实现两个函数,分别用来序列化和反序列化二叉树
# -*- 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
ss = ['']
def dfs(p):
if not p:
ss[0]+='-#'
return
ss[0]+=('-'+str(p.val))
dfs(p.left)
dfs(p.right)
dfs(root)
return ss[0]
def Deserialize(self, s):
# write code here
ss = s[1:].split('-')
i = [-1]
def dfs():
i[0]+=1
if ss[i[0]]=='#': return None
root = TreeNode(int(ss[i[0]]))
root.left = dfs()
root.right = dfs()
return root
return dfs()