【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

猜你喜欢

转载自www.cnblogs.com/seyjs/p/10205544.html