题解 | #序列化二叉树#
序列化二叉树
http://www.nowcoder.com/practice/cf7e25aa97c04cc1a68c8f040e71fb84
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None #这道题里的序列化和反序列化都用的递归,思路比较简单。序列化用的前序遍历;反序列化根据前序遍历的顺序,依次处理root、左子树和右子树 class Solution: def __init__(self): self.split_s=[] def Serialize(self, root): # write code here if not root: return "#," return str(root.val)+","+self.Serialize(root.left)+self.Serialize(root.right) def Deserialize(self, s): if s==None: return None if s=="#": return None self.split_s=s.split(',') return self.construct() def construct(self): if self.split_s[0]=="#": self.split_s=self.split_s[1:] return None node=TreeNode(int(self.split_s[0])) node.left=None node.right=None self.split_s=self.split_s[1:] node.left=self.construct() node.right=self.construct() return node # write code here