二叉树的序列化和反序列化

 二叉树的序列化是指把二叉树保存成字符串的形式,而二叉树的反序列化则表示把保存成字符串形式的数据恢复成二叉树。
 根据二叉树序列化的定义,二叉树序列化比较简单,用#表示为空,保存时,每个节点用逗号隔开,这样,用前序遍历的形式就可以很容易序列化二叉树。反序列化也同理:

class Solution:
    def __init__(self):
        self.index=-1
    def Serialize(self, root):
        # write code here
        if root==None:
            return "#,"
        return str(root.val)+','+self.Serialize(root.left)+self.Serialize(root.right)
    def Deserialize(self, s):
        # write code here
        self.index+=1
        temp=s.split(',')
        res=None
        if temp[self.index]!='#':
            res=TreeNode(int(temp[self.index]))
            res.left=self.Deserialize(s)
            res.right=self.Deserialize(s)
        return res

另一种思路是采用层序遍历来做,代码如下:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def __init__(self):
        self.index = 0

    def Serialize(self, root):
        # write code here
        if root == None:
            return '#'
        ss = []
        res = []
        ss.append(root)
        while len(ss) > 0:
            top = ss.pop(0)
            if top != None:
                res.append(str(top.val))
                if top.left != None:
                    ss.append(top.left)
                else:
                    ## 注意, 空节点也需要存下
                    ss.append(None)
                if top.right != None:
                    ss.append(top.right)
                else:
                    ss.append(None)
            else:
                res.append('#')
        return ','.join(res)


    def Deserialize(self, s):
        # write code here
        a = s.split(',')
        if len(a) == 0 or a[0] == '#':
            return None
        ss = []
        res = TreeNode(int(a[0]))
        ss.append(res)
        i = 1
        while len(ss) > 0 and i+1 < len(a):
            top = ss.pop(0)
            if top != None:
                leftVal, rightVal = a[i], a[i+1]
                leftChild = None
                if leftVal != '#':
                    leftChild = TreeNode(int(leftVal))
                top.left = leftChild
                ss.append(leftChild)

                rightChild = None
                if rightVal != '#':
                    rightChild = TreeNode(int(rightVal))
                top.right = rightChild
                ss.append(rightChild)
                i += 2
        return res      

你可能感兴趣的:(编程与算法,剑指offer,数据结构,算法,leetcode,数据结构)