最简单的python解题,怎么遍历放入就怎么反序列回去,无关是前序遍历还是层次遍历,此处我使用的是先序遍历
class Solution:
str1 = []
def Serialize(self, root):
# write code here
if root == None:
self.str1.append("#")
return self.str1
self.str1.append(str(root.val))
self.Serialize(root.left)
self.Serialize(root.right)
return self.str1
start=-1
def Deserialize(self, s):
# write code here
self.start=self.start+1;
if self.start>=len(s) or s[self.start]=="#" or s==None :return ;
cur=TreeNode(int(s[self.start]))
cur.left=self.Deserialize(s)
cur.right=self.Deserialize(s)
return cur