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

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

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

样例

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

  3
 / \
9  20
  /  \
 15   7

思路:层次遍历,若为叶子节点,则其子节点填“#”

"""
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):
        # write your code here
        if root is None:
            return []
            
        node = [root]
        result = []
        while node:
            new_node = []
            for i in node:
                if i == "#":
                    result.append("#")
                    continue
                else:
                    result.append(i.val)
                    
                if i.left is not None:
                    new_node.append(i.left)
                else:
                    new_node.append("#")
                    
                if i.right is not None:
                    new_node.append(i.right)
                else:
                    new_node.append("#")
            
            node = new_node
        
        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):
        # write your code here
        
        if data == []:
            return None
        
        root = TreeNode(data[0])
        queue = [root]
        isLeftChild = True
        index = 0
        
        for val in data[1:]:
            if val is not "#":
                node = TreeNode(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

反序列化的时候,需要index和isLeftChild两个指示器辅助跳过叶子节点

posted @ 2018-01-04 15:26  Tom_NCU  阅读(136)  评论(0编辑  收藏  举报