• 【leetcode】297. Serialize and Deserialize Binary Tree


    题目如下:

    Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

    Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

    Example: 

    You may serialize the following tree:
    
        1
       / 
      2   3
         / 
        4   5
    
    as "[1,2,3,null,null,4,5]"
    

    Clarification: The above format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

    Note: Do not use class member/global/static variables to store states. Your serialize and deserialize algorithms should be stateless.

    解题思路:题目对于序列化的格式没有限定,给予了充分发挥的空间。我的方法是把每个节点表示成 节点编号:节点值 这种格式,记根节点的编号为1,那么其左右子节点的编号就是2和3,Example的二叉树序列化之后的结果就是: 1:1;2:2;3:3;6:4;7:5 。

    代码如下:

    # Definition for a binary tree node.
    class TreeNode(object):
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    
    class Codec:
        path = ''
        def serialize(self, root):
            """Encodes a tree to a single string.
            :type root: TreeNode
            :rtype: str
            """
            if root == None:
                return ''
            self.path = ''
            self.recursive(root,1)
            return self.path[:-1]
        def recursive(self,node,inx):
            self.path += str(inx) + ':' + str(node.val) + ';'
            if node.left != None:
                self.recursive(node.left,2*inx)
            if node.right != None:
                self.recursive(node.right, 2*inx+1)
    
        def deserialize(self, data):
            """Decodes your encoded data to tree.
    
            :type data: str
            :rtype: TreeNode
            """
            print data
            if data == '':
                return None
            itemlist =  data.split(';')
            dic = {}
            for i in itemlist:
                item = i.split(':')
                dic[int(item[0])] = int(item[1])
            root = TreeNode(dic[1])
            queue = [(1,root)]
            while len(queue) > 0:
                inx,parent = queue.pop(0)
                if 2*inx in dic:
                    l_child = TreeNode(dic[2*inx])
                    parent.left = l_child
                    queue.append((2 * inx, l_child))
                if 2*inx+1 in dic:
                    r_child = TreeNode(dic[2*inx+1])
                    parent.right = r_child
                    queue.append((2*inx+1, r_child))
            return root
  • 相关阅读:
    关于排列问题的一系列归类
    [翻译] 服务定位器是反模式
    [翻译] Autofac 入门文档
    关系,表和封闭世界假定
    Elasticsearch实现类似 like '?%' 搜索
    LVS + keepalived(DR) 实战
    kafka集群中常见错误的解决方法:kafka.common.KafkaException: Should not set log end offset on partition
    Elasticsearch1.7服务搭建与入门操作
    Ubuntu下安装Tomcat7
    VB编程技巧推荐
  • 原文地址:https://www.cnblogs.com/seyjs/p/10205544.html
Copyright © 2020-2023  润新知