One - One Code All

Blog Content

Lintcode-7:二叉树的序列化和反序列化

Python 每日一练 算法 LintCode   2010-03-07 16:23:02

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

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

 注意事项
There is no limit of how you deserialize or serialize a binary tree, LintCode will take your output ofserialize as the input of deserialize, it won't check the result of serialize.


样例
给出一个测试数据样例, 二叉树{3,9,20,#,#,15,7},表示如下的树结构:

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

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

 
思路:在这里使用先根遍历来实现;
   本题目难点在于,里面穿插关于字符串和整数间的互相转换。
   在序列化时,空节点的表示,不同节点值之间的分割。
   在反序列化时,字符串每个字符遍历时的控制条件和操作,以及将字符串转换为整数;


# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from collections import deque
class Solution:
    def Serialize(self, root):
        vals = []
        def preOrder(root):
            if not root:
                vals.append('#')
            else:
                vals.append(str(root.val))
                preOrder(root.left)
                preOrder(root.right)
        preOrder(root)
        return ' '.join(vals)

    def Deserialize(self, s):
        vals = deque(val for val in s.split())
        def build():
            if vals:
                val = vals.popleft()
                if val == '#':
                    return None
                root = TreeNode(int(val))
                root.left = build()
                root.right = build()
                return root
        return build()



上一篇:Lintcode-6:合并排序数组 II
下一篇:Lintcode-8:旋转字符串

The minute you think of giving up, think of the reason why you held on so long.