lintcode 7. 二叉树的序列化和反序列化 Python代码

 

'''

7. 二叉树的序列化和反序列化
描述
设计一个算法,并编写代码来序列化和反序列化二叉树。将树写入一个文件被称为“序列化”,读取文件后重建同样的二叉树被称为“反序列化”。

如何反序列化或序列化二叉树是没有限制的,你只需要确保可以将二叉树序列化为一个字符串,并且可以将字符串反序列化为原来的树结构。

对二进制树进行反序列化或序列化的方式没有限制,LintCode将您的serialize输出作为deserialize的输入,它不会检查序列化的结果。

您在真实的面试中是否遇到过这个题?  
样例
给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7},表示如下的树结构:

  3
 / \
9  20
  /  \
 15   7
我们的数据是进行BFS遍历得到的。当你测试结果wrong answer时,你可以作为输入调试你的代码。

你可以采用其他的方法进行序列化和反序列化。
'''

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
class Solution:


    def serialize(self, root):
        if root is None:
            return "{}"

        queue = [root]
        index = 0
        while index < len(queue):
            if queue[index] is not None:
                queue.append(queue[index].left)
                queue.append(queue[index].right)
            index += 1

        while queue[-1] is None:
            queue.pop()

        return '{%s}' % ','.join([str(node.val) if node is not None else '#'
                                  for node in queue])


    def deserialize(self, data):
        data = data.strip('\n')

        if data == '{}':
            return None

        vals = data[1:-1].split(',')  #['3', '9', '20', '#', '#', '15', '7']

            
        root = TreeNode(int(vals[0]))  #[<__main__.TreeNode object at 0x1057d44a8>]

        queue = [root]  #[<__main__.TreeNode object at 0x1057d44a8>]

        isLeftChild = True
        index = 0

        for val in vals[1:]:
            if val is not '#':
                node = TreeNode(int(val))
                if isLeftChild:
                    queue[index].left = node
                else:
                    queue[index].right = node
                queue.append(node)

            if not isLeftChild:
                index += 1
            isLeftChild = not isLeftChild

        return root

my_solution = Solution()
data = "{3,9,20,#,#,15,7}"
deser = my_solution.deserialize(data) #把人能识别的东西序列化为机器能识别的. [<__main__.TreeNode object at 0x10d9e4198>]

print(deser)
ser = my_solution.serialize(deser)  #把机器能识别的反序列化为人能识别的
print(ser)

输出:
<__main__.TreeNode object at 0x10d9e4198>
{3,9,20,#,#,15,7}
[Finished in 0.0s]

认识你是我们的缘分,同学,等等,记得关注我。

 

微信扫一扫
关注该公众号

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值