1. 程式人生 > >Serialize and Deserialize Binary Tree

Serialize and Deserialize Binary Tree

rest not sta state ppr des note proc binary

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.

序列化和反序列化二叉樹。解法主要是兩種層序遍歷和前序遍歷。

前序遍歷基本采用遞歸寫法,需要保存一個全局變量來告訴代碼,現在在處理數組的第幾個數字。比較麻煩。

所以這裏給出層序遍歷的代碼:

class Codec:

    def serialize(self, root):
        """Encodes a tree to a single string.
        
        :type root: TreeNode
        :rtype: str
        
""" if root is None: return "" res = [] queue = collections.deque() queue.append(root) while queue: node = queue.popleft() if node: res.append(str(node.val)) queue.append(node.left) queue.append(node.right) else: res.append(#) return ",".join(res) def deserialize(self, data): """Decodes your encoded data to tree. :type data: str :rtype: TreeNode """ if data == "": return None res = data.split(,) queue = collections.deque() root = TreeNode(res[0]) i = 1 queue.append(root) while queue: cur = queue.popleft() leftval = res[i] if leftval != #: left = TreeNode(int(leftval)) cur.left = left queue.append(left) i += 1 rightval = res[i] if rightval != #: right = TreeNode(int(rightval)) cur.right = right queue.append(right) i += 1 return root

註意這裏的寫法對於[1,2,3,null,null,4,5]的序列化結果為“1,2,3,#,#,4,5,#,#,#,#”

同時註意這裏的反序列化實際利用第一層只有根節點的信息,所以先放到queue中。

Serialize and Deserialize Binary Tree