序列化二叉树 python

序列化二叉树

http://www.nowcoder.com/questionTerminal/cf7e25aa97c04cc1a68c8f040e71fb84

#主要是递归的思路
class Solution:
    ss = []
    def Serialize(self, root):
        if root is None:
            return '#,'
        return str(root.val) +','+ self.Serialize(root.left) + self.Serialize(root.right)

    def Deserialize(self, s):
        if len(s)==0:
            return None
        if s[0] == '#':
            return None
        self.ss = s.split(',')
        return self.reconstruct()

    def reconstruct(self):
        val = self.ss[0]
        if val == '#':
            self.ss = self.ss[1:]
            return None
        val = int(val)
        root = TreeNode(val)
        self.ss = self.ss[1:]
        root.left = self.reconstruct()
        root.right = self.reconstruct()
        return root
全部评论

相关推荐

totoroyyw:千年老妖😂
投递华为等公司10个岗位
点赞 评论 收藏
分享
评论
3
收藏
分享
牛客网
牛客企业服务