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.

你可能感兴趣的:(2018-10-17 Serialize and Deserialize Binary Tree [M])