2018-10-17 Serialize and Deserialize Binary Tree [M]

  1. Serialize and Deserialize Binary Tree
    LC: 297
    Design an algorithm and write code to serialize and deserialize a binary tree. Writing the tree to a file is called 'serialization' and reading back from the file to reconstruct the exact same binary tree is 'deserialization'.

Example
An example of test data: Binary tree {3,9,20,#,#,15,7}, denote the following structure:

3
/ \
9 20
/ \
15 7
Our data serialization use bfs traversal. This is just for when you got wrong answer and want to debug the input.

You can use other method to do serializaiton and deserialization.

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

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
class Solution:
    """
    @param root: An object of TreeNode, denote the root of the binary tree.
    This method will be invoked first, you should design your own algorithm 
    to serialize a binary tree which denote by a root node to a string which
    can be easily deserialized by your own "deserialize" method later.
    """
    def serialize(self, root):
        # BFS problem, need queue
        result = []
        if not root:
            return result

        # key1: add root to initiate it
        queue = [root]
        while queue:
            node = queue.pop(0)
            if node == None:
                result.append('#')
                continue
            # traverse in level-wise order
            result.append(str(node.val))
            # key2: put the neighbors into the queue
            queue.append(node.left)
            queue.append(node.right)
        return result
    """
    @param data: A string serialized by your serialize method.
    This method will be invoked second, the argument data is what exactly
    you serialized at method "serialize", that means the data is not given by
    system, it's given by your own serialize method. So the format of data is
    designed by yourself, and deserialize it here as you serialize it in 
    "serialize" method.
    """
    def deserialize(self, data):
        if not data or data[0] == '#':
            return None

        root = TreeNode(int(data.pop(0)))        
        queue = [root]
        is_left = True
        while data:
            ch = data.pop(0)
            if ch != '#':
                node = TreeNode(int(ch))
                queue.append(node)                
                if is_left:
                    queue[0].left = node
                else:
                    queue[0].right = node
            if not is_left:
                queue.pop(0)
            is_left = not is_left
        return root
  • Time:O(n)
  • SpaceO(n)
    Notes:
  1. deserialization still needs a queue. This queue is to reconstruct the queue I created in serialization. Similarly, it performs level-wise traversal but skips all None this time.
  2. is_left is a flag specifically for this problem as I do not know next ch is left or right node. (one parent node may have 0, 1 or 2 child nodes)
  3. It is easier to understand if I imagine data and queue as two parallel streamlines.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,499评论 0 10
  • 朦胧的天空, 雪轻轻飘舞, 无声无息地落在地上, 冰天的世界瞬间雪白。 可是, 我在南方, 渴望一睹雪的芳容。 雾...
    安徒生里的童话阅读 158评论 0 1
  • 一.自我认知 1.学历:中专(正在上大专) 2.年龄:19 3.人脉资源:匮乏 二、内心独白 我现在对自己的未来没...
    半叶_0d54阅读 206评论 2 0