1. 程式人生 > >【leetcode】297. Serialize and Deserialize Binary Tree

【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