圆月山庄资源网 Design By www.vgjia.com

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python数据结构与算法教程》、《Python加密解密算法与技巧总结》、《Python编码操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》

希望本文所述对大家Python程序设计有所帮助。

标签:
Python,序列化,反序列化,二叉树

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com