今天就跟大家聊聊有关怎么在Python中实现一个序列化和反序列化的二叉树算法,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
序列化二叉树
先序遍历二叉树
def recursionSerialize(self, root): series = '' if root == None: series += ',$' else: series += (',' + str(root.val)) series += self.recursionSerialize(root.left) series += self.recursionSerialize(root.right) return series def Serialize(self, root): return self.recursionSerialize(root)[1:]
结果:
root = TreeNode(11) root.left = TreeNode(2) root.right = TreeNode(3) series = Solution().Serialize(root) print(series) >>>11,2,$,$,3,$,$
反序列化
先构建根节点,然后左节点,右节点,同样是递归
注意由于使用的是字符串的表示形式,可以先转化为list,
print(series.split(',')) >>>['11', '2', '$', '$', '3', '$', '$']
然后再处理就不需要将大于10的数字转换过来了:
def getValue(self, s, sIndex): #处理超过10的数字,将数字字符转变为数字 val = 0 while ord(s[sIndex]) <= ord('9') and ord(s[sIndex]) >= ord('0'): val = val * 10 + int(s[sIndex]) sIndex += 1 return val, sIndex - 1
下面是反序列化的递归函数:
def Deserialize(self, s): if self.sIndex < len(s): if s[self.sIndex] == ',': self.sIndex += 1 if s[self.sIndex] == '$': return None val, self.sIndex = self.getValue(s, self.sIndex) treeNode = TreeNode(val) self.sIndex += 1 treeNode.left = self.Deserialize(s) self.sIndex += 1 treeNode.right = self.Deserialize(s) return treeNode
完整解法
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def __init__(self): self.sIndex = 0 def recursionSerialize(self, root): series = '' if root == None: series += ',$' else: series += (',' + str(root.val)) series += self.recursionSerialize(root.left) series += self.recursionSerialize(root.right) return series def Serialize(self, root): return self.recursionSerialize(root)[1:] def getValue(self, s, sIndex): #处理超过10的数字,将数字字符转变为数字 val = 0 while ord(s[sIndex]) <= ord('9') and ord(s[sIndex]) >= ord('0'): val = val * 10 + int(s[sIndex]) sIndex += 1 return val, sIndex - 1 def Deserialize(self, s): if self.sIndex < len(s): if s[self.sIndex] == ',': self.sIndex += 1 if s[self.sIndex] == '$': return None val, self.sIndex = self.getValue(s, self.sIndex) treeNode = TreeNode(val) self.sIndex += 1 treeNode.left = self.Deserialize(s) self.sIndex += 1 treeNode.right = self.Deserialize(s) return treeNode
看完上述内容,你们对怎么在Python中实现一个序列化和反序列化的二叉树算法有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。